JavaScriptFundamental (ES6), part 1
entries() on arrays and Maps in JavaScript
57 keys, values and entries on an array and a Map
fairNumber a list with array.entries() and a destructuring for...of. Then do the same over a Map, note the argument order Map.prototype.forEach uses, and show that the iterator these methods return is single-use while Object.keys hands back an array.
Stuck? Three hints, smallest first
- 1.
for (const [i, item] of arr.entries())is the index-and-value loop. - 2. A
Mapiterates as entries by default, so[...map]and[...map.entries()]agree. - 3.
forEachon both arrays and Maps passes the value first, then the key.
const stalls = ['gari', 'rice', 'beans'];
const arrayEntries = [...stalls.entries()];
const numbered = [];
for (const [i, name] of stalls.entries()) numbered.push(`${i + 1}. ${name}`);
const arrayKeys = [...stalls.keys()];
const keyKinds = arrayKeys.map((k) => typeof k);
const arrayValues = [...stalls.values()];
const prices = new Map([['gari', 250000], ['rice', 480000]]);
const mapDefault = [...prices];
const mapEntries = [...prices.entries()];
const total = [...prices.values()].reduce((sum, kobo) => sum + kobo, 0);
const forEachOrder = [];
prices.forEach((value, key) => forEachOrder.push(`${key}=${value}`));
const iterator = prices.keys();
const drained = [...iterator];
const again = [...iterator]; // an iterator is used up
const shapes = [Array.isArray(Object.keys({ a: 1 })), Array.isArray([...prices.keys()]), Array.isArray(prices.keys())];
console.log('array entries:', arrayEntries);
console.log('numbered :', numbered);
console.log('array keys :', arrayKeys, keyKinds);
console.log('map default :', mapDefault);
console.log('total :', total, '| forEach order:', forEachOrder);
console.log('iterator :', drained, 'then', again);
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('entries on an array pairs index with value', arrayEntries, [[0, 'gari'], [1, 'rice'], [2, 'beans']]);
test('destructuring the pair in a for...of numbers a list', numbered, ['1. gari', '2. rice', '3. beans']);
test('array keys are real numbers here, unlike for...in', [arrayKeys, keyKinds], [[0, 1, 2], ['number', 'number', 'number']]);
test('values is just the elements again', arrayValues, ['gari', 'rice', 'beans']);
test('a Map iterates as entries by default', [mapDefault, mapEntries], [[['gari', 250000], ['rice', 480000]], [['gari', 250000], ['rice', 480000]]]);
test('so its values can be totalled', total, 730000);
test('forEach on a Map hands you the value first and the key second', forEachOrder, ['gari=250000', 'rice=480000']);
test('the iterator these methods return is single-use', [drained, again], [['gari', 'rice'], []]);
test('Object.keys returns an array; keys() returns an iterator', shapes, [true, true, false]);
entries() is the answer to "I need the index too" without a for loop or a stray counter, and it destructures in the loop header so the body never mentions [0] or [1]. The keys() on an array is worth contrasting with for...in from exercise 51: this one yields the number 0, that one yields the string '0'.
Two traps sit close together. forEach passes value before key, on arrays and Maps alike, so map.forEach((key, value) => ...) reads perfectly and is backwards — while for...of over the same Map gives [key, value] in that order. And the object these methods return is an iterator, not a collection: spread it twice and the second attempt is empty, because it has no rewind. Object.keys is different in kind — a plain array, reusable, with length and every array method.