Array From Method
Array.from() creates a new array from anything that is iterable, such as a string, a Set or a Map, or from an array-like object, which is an object with a length property and numbered keys. It is a static method, so it is called on Array itself rather than on an array.
console.log(Array.from('tea'));console.log(Array.from(new Set(['red', 'green', 'red'])));console.log(Array.from({ length: 2, 0: 'first', 1: 'second' }));This prints:
[ 't', 'e', 'a' ][ 'red', 'green' ][ 'first', 'second' ]Turning a Set back into an array is a common way to remove duplicates, because the Set keeps each value only once.
Mapping as it goes
Section titled “Mapping as it goes”A second argument is a function that is applied to each element on the way in, which saves a separate call to map(). Combined with an object that has only a length, it builds an array of a given size:
console.log(Array.from({ length: 5 }, (_, index) => index * index));console.log(Array.from('12345', Number));This prints:
[ 0, 1, 4, 9, 16 ][ 1, 2, 3, 4, 5 ]The object { length: 5 } has no elements, so each one arrives as undefined. The underscore is a common name for a parameter that is not used.
Lists from the page
Section titled “Lists from the page”In the browser, document.querySelectorAll() returns a NodeList, which has forEach() but not map(), filter() or the other array methods. Array.from() turns it into a real array:
const headings = Array.from(document.querySelectorAll('h2'));const headingText = headings.map((heading) => heading.textContent);headingText then holds the text of every h2 on the page, in document order. The spread syntax, [...document.querySelectorAll('h2')], does the same.
It makes a shallow copy
Section titled “It makes a shallow copy”Called on an array, Array.from() copies it. The copy is a new array, so replacing an element in it does not affect the original. Objects inside it are not copied, though, so both arrays hold the same object, and a change to that object shows through both.
const shelf = ['Emma', { title: 'Walden', onLoan: false }];
const copy = Array.from(shelf);copy[0] = 'Persuasion';copy[1].onLoan = true;
console.log(shelf);console.log(copy);This prints:
[ 'Emma', { title: 'Walden', onLoan: true } ][ 'Persuasion', { title: 'Walden', onLoan: true } ]To copy the nested objects too, use structuredClone(), which makes a deep copy. Deep vs Shallow Copy has more on the difference.
Steve Griffith covers this topic in his video Array from Method.