JavaScriptFundamental (ES6), part 1
Convert an array-like object to an array in JavaScript
52 An array-like is not iterable
fairTake an object with numeric keys and a length, try to spread it, then convert it properly. Show two ways, show Array.from's mapping argument, and show that arguments is both array-like and iterable while your object is only the first.
Stuck? Three hints, smallest first
- 1. Spread and
for...ofneedSymbol.iterator. Array-like means only "haslengthand index keys". - 2.
Array.fromworks on both, and takes a second argument that maps each element as it goes. - 3.
Array.from({ length: n }, (_, i) => ...)generates a range from nothing at all.
const arrayLike = { 0: 'gari', 1: 'rice', length: 2 };
const attempt = (fn) => { try { return fn(); } catch (e) { return e.constructor.name; } };
const spreadFails = attempt(() => [...arrayLike]);
const viaFrom = Array.from(arrayLike);
const viaSlice = Array.prototype.slice.call(arrayLike);
const mapped = Array.from(arrayLike, (item) => item.toUpperCase());
const range = Array.from({ length: 4 }, (_, i) => i * 250);
const noLength = Array.from({ a: 1 });
const shortLength = Array.from({ 0: 'a', 1: 'b', length: 1 });
function collect() {
return [...arguments]; // arguments is iterable
}
const spreadArguments = collect('gari', 'rice');
const iteratorPresence = [typeof arrayLike[Symbol.iterator], typeof [][Symbol.iterator]];
const stringSpread = [...'Yaba'];
const setSpread = [...new Set(['a', 'a', 'b'])];
console.log('spread :', spreadFails);
console.log('Array.from:', viaFrom, '| slice.call:', viaSlice);
console.log('mapped :', mapped, '| generated range:', range);
console.log('no length:', noLength, '| length shorter than the keys:', shortLength);
console.log('arguments:', spreadArguments, '| iterator present?', iteratorPresence);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('spreading an array-like throws, because it has no iterator', spreadFails, 'TypeError');
test('Array.from reads length and the index keys instead', viaFrom, ['gari', 'rice']);
test('the pre-ES6 slice.call trick does the same job', viaSlice, ['gari', 'rice']);
test('Array.from takes a mapping function as its second argument', mapped, ['GARI', 'RICE']);
test('so length alone is enough to generate a range', range, [0, 250, 500, 750]);
test('length decides what is read: none gives an empty array, a short one truncates', [noLength, shortLength], [[], ['a']]);
test('arguments is array-like AND iterable, so spread works on it', spreadArguments, ['gari', 'rice']);
test('only the real array has Symbol.iterator', iteratorPresence, ['undefined', 'function']);
test('strings and Sets have it too, so both spread', [stringSpread, setSpread], [['Y', 'a', 'b', 'a'], ['a', 'b']]);
Two unrelated ideas wear similar clothes. Array-like is a shape: a length and keys 0..length-1, which is what arguments, a NodeList and an HTMLCollection all have. Iterable is a capability: a Symbol.iterator method, which is what spread, for...of, destructuring, Promise.all and new Map(...) actually require. Many DOM collections now have both; a hand-built object has only the first, which is why the spread throws.
Array.from is the bridge and handles either. The seventh assertion is the trap in the array-like path: it trusts length completely, so a wrong length silently truncates or pads with undefined rather than complaining. Its mapping argument is not a nicety either — Array.from({length: 3}).map(...) works, but new Array(3).map(...) does not, because holes are skipped.