Sub topic 16
Making Arrays from Iterables and Array-Likes
This chapter assumes you know arrow functions, object literals, and the map and reduce methods from earlier chapters. You will learn to turn values that look like arrays, or that can be looped over, into real arrays that have every array method.
Two kinds of "almost arrays"
JavaScript has many values that hold a sequence but are not arrays:
- An iterable is any value that
for...ofcan loop over. Strings,Set,Map, and DOMNodeListobjects are iterables. - An array-like is an object with a numeric
lengthproperty and indexed keys (0,1, ...). Theargumentsobject inside a regular function is one, and so is a plain object such as{ length: 2, 0: 'a', 1: 'b' }.
Neither kind has map, filter, or reduce. To use those methods, convert the value first.
Array.from
Array.from(source, mapFn) builds a new array. It accepts both iterables and array-likes. The optional second argument is a mapping function with the same (element, index) signature that map uses.
console.log(Array.from('abc')); // ['a', 'b', 'c']
console.log(Array.from(new Set([1, 2, 2, 3]))); // [1, 2, 3]
console.log(Array.from(new Map([['x', 1]]))); // [['x', 1]]
const arrayLike = { length: 2, 0: 'a', 1: 'b' };
console.log(Array.from(arrayLike)); // ['a', 'b']
function sum() {
return Array.from(arguments).reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6If you pass an object with only a length, you can generate an array from scratch. Each missing index reads as undefined, and the mapping function fills it in:
const evens = Array.from({ length: 4 }, (_, i) => i * 2);
console.log(evens); // [0, 2, 4, 6]Passing the mapping function does the same work as Array.from(x).map(fn), but it skips building an intermediate array.
Spread versus Array.from
Spread syntax ([...value]) only works on iterables. It throws on array-likes:
console.log([...new Set(['a', 'a', 'b'])]); // ['a', 'b']
try {
[...{ length: 2, 0: 'a', 1: 'b' }];
} catch (err) {
console.log(err instanceof TypeError); // true (not iterable)
}| Source | `[...x]` | `Array.from(x)` |
|---|---|---|
| String, Set, Map, NodeList | Works | Works |
| `arguments` | Works | Works |
| `{ length: n, ... }` | TypeError | Works |
| Needs mapping while converting | Add `.map()` | Second argument |
Array.of and the constructor pitfall
The Array constructor behaves differently when it gets exactly one number. In that case it creates empty slots instead of an element:
console.log(Array(7).length); // 7 (seven empty slots)
console.log(Array(7, 8)); // [7, 8]
console.log(Array.of(7)); // [7]
console.log(Array.of(7, 8)); // [7, 8]Array.of always treats its arguments as elements. Use it, or a plain literal like [7], when you need an array built from given values.
Exercise
Write one expression that takes the string 'banana', removes duplicate letters, and returns them as an array of uppercase letters.
Show answer
Array.from(new Set('banana'), ch => ch.toUpperCase()) returns ['B', 'A', 'N']. The Set keeps the first occurrence of each letter, and the mapping function uppercases each one during the conversion.
Exercise
Why does Array(3).map((, i) => i) return an array of three empty slots, while Array.from({ length: 3 }, (, i) => i) returns [0, 1, 2]?
Show answer
Array(3) creates a sparse array with no elements, and map skips holes, so the callback never runs. Array.from reads each index from 0 up to length - 1, treats missing ones as undefined, and calls the mapping function for every index.