JavaScript - Arrays - From

javascript-arrays

// JavaScript - Array.from

The Array.from() method creates a new Array instance from an array-like or 
iterable object.

Array.from("foo");
// ["f", "o", "o"]

Array.from(arrayLike[, mapFn[, contextObject]])

1. arrayLike: An array-like or iterable object to convert to an array.
2. mapFn: Optional. Map function to call on every element of the array.
3. contextObject: Optional. Value to use as this when executing mapFn.

Obviously the Array.from method returns the new array. Array.from() lets you 
create Arrays from:

1. array-like objects (objects with a length property and indexed elements)
2. iterable objects (objects where you can get its elements, such as Map and Set).

Array.from() has an optional parameter mapFn, which allows you to execute a map 
function on each element of the array (or subclass object) that is being created. 
More clearly, Array.from(obj, mapFn, thisArg) has the same result as 
Array.from(obj).map(mapFn, thisArg), except that it does not create an 
intermediate array. This is especially important for certain array subclasses, 
like typed arrays, since the intermediate array would necessarily have values 
truncated to fit into the appropriate type.

In ES2015, the class syntax allows for sub-classing of both built-in and user 
defined classes; as a result, static methods such as Array.from are "inherited" 
by subclasses of Array and create new instances of the subclass, not Array.

// Array from a String:
Array.from("foo"); 
// ["f", "o", "o"]

// Array from a Set
var s = new Set(["foo", window]); 
Array.from(s); 
// ["foo", window]

// Array from a Map
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m); 
// [[1, 2], [2, 4], [4, 8]]

// Array from an Array-like object (arguments)
Array.from(arguments);

// Using arrow functions and Array.from
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);      
// [2, 4, 6]

// Generate a sequence of numbers
Array.from({length: 5}, (v, k) => k);    
// [0, 1, 2, 3, 4]
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License