Skip to main content

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 Map or Set.
  • 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.
tip

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:

// creating an array from a string 
Array.from('JavaScript');

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.

let arrayLike = {0: 5, 1: 7, 2: 1, length: 3};
Array.from(arrayLike);

// Output
[5, 7, 1]

Sequence of Numbers with the from() Method

(Creating Array with N elements, 1...N)

Array.from({ length: 5 }, (_, i) => i+1);

// Output
[1, 2, 3, 4, 5]

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]
Array.from([2,4,6], 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

let defaultValue = 0;
Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => defaultValue ));
// Output:
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

Mapping object properties into arrays

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' ]

Using Array.from() in JavaScript with a this Value

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]

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

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']

NodeList & HTMLCollection into an Array

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.