The Array.from() method creates a shallow-copied array instance from an array like object or an iterable. The iterable object could be an array, a string, a set, an object or anything with an iterable property.
Syntax:
Array.from(iterable, mapFunction, thisArg)
where,
iterable: the object to convert into an array
mapFunction (optional): A function to call on each element of the array. The mapFunction accepts two parameters as any regular Javascript map function does. The first parameter is the current element and the second one its index in the array.
thisArg (optional): An object to pass as this when using the map function.
Let's look at their use cases in brief
1. Generate numbers up to a specific range:
The traditional method of generating numbers up to a specific range is always to use loops. But the Array.from() method is a one-liner which does the same job as the Javascript loops in this case.
// The traditional method:
const numberCount = [];
for( let i=0; i < 5; i++){
numberCount.push( i+1 )
}
console.log(numberCount) // Output: [ 1, 2, 3, 4, 5 ]
// Using Array.from() method to do the same job:
Array.from( { length: 5 }, (_, index)=> index+1 )
// Output: [ 1, 2, 3, 4, 5 ]
2. Creating a Matrix:
While working with mathematical concepts or engaging in complex use cases, dealing with multi-dimensional arrays can be a cumbersome task, especially during the creation phase. To create one, we use nested for
loops, and a small mistake in the logic can end up in vain. But the task is made easier with Array.from() method and it is easy to debug as well.
// Create a grid of Default value
let defaultValue = 0;
let grid = Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => defaultValue ));
// Output: [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
// Create a grid with numbers in the increasing order
let grid = Array.from({ length: 3 }, () => Array.from({ length: 3 }, (_, i) => i+1));
// Output: [ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
3. Mapping object properties into arrays
If you wish to map either the keys or values of an object into an array, it is better to use Array.from()
in addition to Object
methods
const user = { name: 'Ram', age: 23, city: 'Chennai' }
const userInfo = Array.from( Object.values(user) )
// Output: [ 'Ram', 23, 'Chennai' ]
4. Creating an HTML nodelist
let listItems = Array.from( { length: 5 }, (item, index)=>{
const item = document.createElement('li');
item.textContent = index + 1;
return item
})
// Output: NodeList [ <li>, <li>, <li>, <li>, <li> ]
5. Converting NodeList into an Array
In addition to the previous use case at 4, the DOM items could be converted back into arrays using Array.from()
method
const listItems = document.querySelectorAll('.listItems')
const listItemsArray = Array.from( listItems )
6. Customizing array elements
Customizing array elements is made easier with Array.from()
javascript method. The Array.from() method creates a shallow copy of the array being passed and manipulates each element while creating a new array. Let's get it clear from the following example.
const numbers = [ 1, 2, 3, 4, 5 ]
const multiplyByTwo = Array.from( numbers, (number)=>number*2 )
// Output: [ 2, 4, 6, 8, 10 ]
// Strings can be manipulated as well
const tags = [ webDev, grateful, mentorship, frontend ]
const twitterTags = Array.from( tags, ( tag, index )=>'#'+tag )
//Output: [ '#webDev', '#grateful', '#mentorship', '#frontend' ]
7. Creating a character frequency map
Array.from()
can be used to find how frequently a letter occurs in a sentence or in a given passage. We could achieve this by simply utilising some basic JavaScript functions and methods.
const greet = 'Hello, world!';
const freqMap = Array.from( greet, ( letter )=>({[letter]: greet.split( letter ).length-1 }))
// Output:
[
{ H: 1 }, { e: 1 },
{ l: 3 }, { l: 3 },
{ o: 2 }, { ',': 1 },
{ ' ': 1 }, { w: 1 },
{ o: 2 }, { r: 1 },
{ l: 3 }, { d: 1 },
{ '!': 1 }
]
These are some use cases of JavaScript's Array.from() method. Please note that, some of the use cases could efficiently be solved using alternate methods available within Javascript, though I wanted to showcase the abilities of this method. For details about the basics and more basic examples, visit the official MDN docs page.
Top comments (6)
Hey! Thank you for article!
Just want to add Object.value already returns Array so you don't have to convert it to Array using Array.from
It's more used with Maps because Map.prototype.values doesn't return an array, it returns map iterator which could be converted to array using Array.from
You are absolutely correct. Thank you for your opinion. Future articles will be free of contradictions. Have a nice day 🙂❤️.
Nice article. Just wanted to say, the character frequency map isn't very efficient (unnecessary quadratic time complexity) and doesn't end up being in a usable form and has multiple same entries. Something simple using
Array#reduce
works, e.g.:Thank you for your feedback. I appreciate the suggestion and accept the same. I just wanted to demonstrate some intermediary use cases of Array.from() method. Indeed Array.reduce() is the more efficient approach. I'll consider incorporating that improvement in the future articles. Have a nice day.!
I wish people would stop writing this exact same article every week.
I wanted to make the article as unique as possible. But if you find the topic boring, I apologise for the same.