Amazing use cases of Array.from() in JavaScript
The Array.from() method returns an array from any array-like or iterable object. The method takes in one compulsory parameter and two other optional parameters:
// Syntax
Array.from(arraylike, mapFunc, thisArg);
The from() method, being a static method, is called using the Array class name.
- arraylike - An Array-like or iterable object to convert to an array.
- This method can create an array from:
- array-like objects - The objects that have length property and have indexed elements like
String. - Iterable objects like
MaporSet.
- array-like objects - The objects that have length property and have indexed elements like
- This method can create an array from:
- mapFunc (optional) - This is an optional parameter. The Map function is called on each element.
- thisArg (optional) - This value is used when executing mapFunc as this. It is also optional.
Array.from(obj, mapFunc, thisArg) is equivalent to Array.from(obj).map(mapFunc, thisArg).
from() Method with Array-like Objects
To see how this works, let’s create an array from a string using the Array.from() method:
- Array.from()
- JS split()
- Result
// creating an array from a string
Array.from('JavaScript');
// creating an array from a string
'JavaScript'.split('');
// Output
['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
In the example above, the Array.from() method returned an array of the string. You can also use the method to return an array from any object with a length property that specifies the number of elements in the object.
- Sample 1
- Sample 2
- With Map fn.
let arrayLike = {0: 5, 1: 7, 2: 1, length: 5};
Array.from(arrayLike);
// Output
[5, 7, 1, undefined, undefined]
let arrayLike = {0: 5, 1: 7, 2: 1, length: 3};
Array.from(arrayLike);
// Output
[5, 7, 1]
let arrayLike = {0: 1, 1: 2, 2: 3, length: 3};
Array.from(arrayLike, val => val * 2);
// Output
// [2,4,6]
Array.from(arrayLike, (val, i) => i * 2);
// Output
// [0,2,4]
Sequence of Numbers with the from() Method
(Creating Array with N elements, 1...N)
- Sample 1
- Sample 2
- Sequence from 1
- Traditional
- Others
Array.from({ length: 5 }, (value, index) => value);
// Output
[undefined, undefined, undefined, undefined, undefined]
Array.from({ length: 5 }, (value, index) => index);
// Output
[0, 1, 2, 3, 4]
Array.from({ length: 5 }, (_, i) => i+1);
// Output
[1, 2, 3, 4, 5]
const numberCount = [];
for( let i=0; i < 5; i++) {
numberCount.push(i + 1);
}
console.log(numberCount);
// Output
[1, 2, 3, 4, 5 ]
Array.from(Array(10).keys());
// Using Spread Operator
[...Array(10).keys()];
// Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[...Array(10).keys()].map(x => ++x);
Array.from(Array(10)).map((e, i) => i + 1);
Array.from(Array(10), (e, i) => i + 1);
// using Fill and Map
Array(10).fill().map((_, i) => i + 1);
// Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array(3).fill();
// Output
[undefined, undefined, undefined]
Array(3).fill('*');
// Output
['*', '*', '*']
Create a Range of Numbers with the from() Method
const arrayRange = (start, stop, step) =>
Array.from(
{ length: (stop - start) / step + 1 },
(value, index) => start + index * step
);
Let's try the method with a few examples:
// Generate numbers between range 2 and 7
let range = arrayRange(2, 7, 1);
console.log(range); // [2,3,4,5,6,7]
// Generate even numbers between range 2 and 7
let evenRange = arrayRange(2, 7, 2);
console.log(evenRange); // [2,4,6]
// Generate odd numbers between range 1 and 5
let oddRange = arrayRange(1, 5, 2);
console.log(oddRange); // [1,3,5]
from() Method with Mapping Function
Array.from([2,4,6], e => e + 2);
// Output
[4, 6, 8]
- mapFn as arg
- Array with mapFn
Array.from([2,4,6], e => e + 2);
// Output
[4, 6, 8]
Array.from([2,4,6]).map(e => e + 2);
// Output
[4, 6, 8]
from() Method with a Set - creating unique array elements
let myArray = ['apple', 'bird', 'apple', 'chicken', 'egg', 'apple'];
let setArray = new Set(myArray);
// Set(4) {'apple', 'bird', 'chicken', 'egg'}
Array.from(setArray);
// ['apple', 'bird', 'chicken', 'egg']
Creating a Matrix
- With Default value
- inc. order
let defaultValue = 0;
Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => defaultValue ));
// Output:
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
Array.from({ length: 3 }, () => Array.from({ length: 3 }, (_, i) => i + 1));
// Output:
[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
Mapping object properties into arrays
- Object value
- Object key
const user = { name: 'Ram', age: 23, city: 'Chennai' };
Array.from( Object.values(user) );
// Output
// Object.values(user); will also return the same below output.
// Array.from() is not necessary here
[ 'Ram', 23, 'Chennai' ]
const user = { name: 'Ram', age: 23, city: 'Chennai' };
Array.from( Object.keys(user) );
// Output
[ 'name', 'age', 'city' ]
Using Array.from() in JavaScript with a this Value
- Sample 1
- Sample 2
- Sample 3
let doubler = {
factor: 2,
double(x) {
return x * this.factor;
// `this` ref. to `doubler`
}
};
let scores = [5, 6, 7];
Array.from(scores, doubler.double, doubler);
// 3rd arg. `doubler` will help fetch `factor`
// Output
[10, 12, 14]
let doubler = {
factor: 2,
double(x) {
return x * 2;
}
};
let scores = [5, 6, 7];
Array.from(scores, doubler.double);
// Output
[10, 12, 14]
function double(x) {
return x * 2;
}
let scores = [5, 6, 7];
Array.from(scores, double);
// Output
[10, 12, 14]
Array from an Iterable Object
We can generate an array from any object that has a [symbol.iterator] attribute because it also operates on iterable objects.
let even = {
*[Symbol.iterator]() {
for (let i = 0; i < 10; i += 2) {
yield i;
}
}
};
Array.from(even);
// Output
[0, 2, 4, 6, 8]
Map to an Array in JavaScript
- Sample 1
- Sample 2
- Sample 3
const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Mottu');
map.set('user3', 'Patlu');
Array.from(map);
// we can use spread operator also as below
[...map];
// Output
[
['user1', 'John'],
['user2', 'Mottu'],
['user3', 'Patlu']
]
Array.from(map.values());
// Output
['John', 'Mottu', 'Patlu']
const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Mottu');
map.set('user3', 'Patlu');
Array.from(map, (el) => {
return { key: el[0], value: el[1] };
});
// We can use array destructuring to shorten the code above:
Array.from(map, ([key, value]) => ({
key,
value,
}));
// Output
[
{ key: 'user1', value: 'John' },
{ key: 'user2', value: 'Mottu' },
{ key: 'user3', value: 'Patlu' }
]
const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Mottu');
map.set('user3', 'Patlu');
// Map to an array of key-value objects
Array.from(map, ([key, value]) => ({
[key]: value,
}));
// Output
[
{user1: 'John'},
{user2: 'Mottu'},
{user3: 'Patlu'}
]
NodeList & HTMLCollection into an Array
- Html
- JS
<body>
<p class="my-para">Hello world</p>
<p class="my-para">Hello Folks</p>
<p class="my-para">Hello budies</p>
<p class="my-para">Hello Man</p>
</body>
const htmlCollectionz = document.getElementsByClassName('my-para');
// HTMLCollection(4) [p.my-para, p.my-para, p.my-para, p.my-para]
const nodeList = document.querySelectorAll('.my-para');
// NodeList(4) [p.my-para, p.my-para, p.my-para, p.my-para]
// converting into Array
const myArray = Array.from(nodeList);
Array.from(htmlCollectionz);
[...nodeList];
[...htmlCollectionz];
// Output
[p.my-para, p.my-para, p.my-para, p.my-para]
myArray.forEach((el) => {
// Do something with the element
});
getElementsByClassName() and querySelectorAll() are not arrays. They're array-like objects called an HTMLCollection and NodeList respectively. This means that it has some of the same properties and methods as an array, but it is not a true array.
One difference between an HTMLCollection (NodeList) and an array is that an HTMLCollection (NodeList) does not have a forEach() method. So If you need to iterate over the elements in an HTMLCollection (NodeList), you can use a for loop or convert into array using Array.from()
HTMLCollection vs NodeList: If you want a live collection that automatically updates when there's a change in the document, then you should use an HTMLCollection. But if you prefer a static collection that doesn't update with a change in the document, then you should use a NodeList.