patternjavascriptTip
Array.from() for converting iterables and array-like objects
Viewed 0 times
ES2015
Array.fromiterableNodeListarray-likemap function
Problem
DOM NodeLists, arguments objects, Maps, Sets, and generators look like arrays but lack array methods. Spreading [...x] is common but lacks a mapping step and cannot handle array-likes.
Solution
Array.from(iterable, mapFn) converts any iterable or array-like to a real array with an optional mapping function applied in the same pass.
// Array-like with map
Array.from({ length: 5 }, (_, i) => i * 2);
// [0, 2, 4, 6, 8]
// NodeList to array
Array.from(document.querySelectorAll('p'));
// From generator
Array.from(range(5)); // [0, 1, 2, 3, 4]
// Array-like with map
Array.from({ length: 5 }, (_, i) => i * 2);
// [0, 2, 4, 6, 8]
// NodeList to array
Array.from(document.querySelectorAll('p'));
// From generator
Array.from(range(5)); // [0, 1, 2, 3, 4]
Why
Array.from applies mapFn in the same pass as conversion, avoiding an extra .map() allocation. It also handles array-likes (with length and numeric indices) that spread cannot handle.
Gotchas
- [...iterable] and Array.from(iterable) are usually equivalent but Array.from also handles array-likes
- Do not use Array.from on infinite generators without a break condition
- Array.from(string) splits by Unicode code point — safer than split('') for emoji
Code Snippets
Array.from use cases
// Range array without a library
const range = Array.from({ length: 10 }, (_, i) => i + 1);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// Safe Unicode string split
Array.from('hello \u{1F600}');
// ['h', 'e', 'l', 'l', 'o', ' ', '\u{1F600}']Revisions (0)
No revisions yet.