Javascript Array.from()

The JavaScript Array.from() static method creates a shallow-copied Array instance from an array-like or iterable object.

The syntax of the from() method is:

Array.from(arraylike, mapFunc, thisArg)

The from() method, being a static method, is called using the Array class name.


from() Parameters

The from() method takes in:

  • arraylike - Array-like or iterable object to convert to an array.
  • mapFunc (optional) - Map function that is called on each element.
  • thisArg (optional) - Value to use as this when executing mapFunc.

Note: Array.from(obj, mapFunc, thisArg) is equivalent to Array.from(obj).map(mapFunc, thisArg).


Return value from from()

  • Returns a new Array instance.

Note: This method can create Array from:

  • Array-like objects - The objects that have length property and have indexed elements like strings.
  • Iterable objets like Map or Set.

Example 1: Using from() method

// Array from String
let arr1 = Array.from("abc");
console.log(arr1); // [ 'a', 'b', 'c' ]

// Array from Map
let mapper = new Map([
  ["1", "a"],
  ["2", "b"],
]);

let arr2 = Array.from(mapper);
console.log(arr2); // [ [ '1', 'a' ], [ '2', 'b' ] ]

let arr3 = Array.from(mapper.keys());
console.log(arr3); // [ '1', '2' ]

// Array from Set
let set = new Set(["JavaScript", "Python", "Go"]);
let arr4 = Array.from(set);
console.log(arr4); // [ 'JavaScript', 'Python', 'Go' ]

Output

[ 'a', 'b', 'c' ]
[ [ '1', 'a' ], [ '2', 'b' ] ]
[ '1', '2' ]
[ 'JavaScript', 'Python', 'Go' ]

This works for other iterable objects as well.


Example 2: Using from() method with mapFunc

function createArr(arraylike, mapFunc) {
  return Array.from(arraylike, mapFunc);
}

// using arrow function for mapFunc
let arr1 = createArr("123456", (x) => 2 * x);
console.log(arr1); // [ 2, 4, 6, 8, 10, 12 ]

Output

[ 2, 4, 6, 8, 10, 12 ]

Recommended Reading: JavaScript Array map()