JavaScriptFundamental (ES6), part 1
Array.from with a map function in JavaScript
72 Array.from, with the map function nobody uses
easyBuild a fare table from nothing with Array.from({ length: n }, fn). Then use the same call to copy a Set, split a string into code points, read an array-like that is not iterable, and show why new Array(3).map(...) cannot do the job.
Stuck? Three hints, smallest first
- 1.
Array.fromtakes a second argument: a map function, called with(value, index). - 2.
new Array(3)has a length of three and no elements at all, and every array method skips holes. - 3. An object with a
lengthis enough forArray.from; being iterable is not required.
const fares = Array.from({ length: 5 }, (_, i) => 250 + i * 150);
const seats = Array.from({ length: 3 }, (_, i) => `A${i + 1}`);
const holes = new Array(3);
const mappedHoles = holes.map((_, i) => i);
const holesStayedHoles = mappedHoles.every((v) => v === undefined);
const filled = Array.from(holes, (_, i) => i);
const blank = Array.from({ length: 2 });
const blankIsUndefined = blank.every((v) => v === undefined);
const repeated = ['garri', 'rice', 'garri', 'beans'];
const unique = Array.from(new Set(repeated));
const shouted = Array.from('Ikeja', (c) => c.toUpperCase());
const flag = '🇳🇬';
const unitsAgainstPoints = [flag.length, Array.from(flag).length];
const stock = new Map([['garri', 12], ['rice', 4]]);
const asPairs = Array.from(stock);
const labels = Array.from(stock, ([good, count]) => `${good}:${count}`);
const arrayLike = { length: 3, 0: 'Lagos', 2: 'Kano' };
const fromArrayLike = Array.from(arrayLike, (v) => v ?? 'gap');
console.log('fares :', fares, seats);
console.log('holes :', mappedHoles, '| from:', filled);
console.log('unique :', unique, '| shouted:', shouted);
console.log('map :', asPairs, labels, '| array-like:', fromArrayLike);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('length plus a map function builds a table with no source array', fares, [250, 400, 550, 700, 850]);
test('the second argument gets the index, which is usually all you need', seats, ['A1', 'A2', 'A3']);
test('map cannot fill holes: it skips every one of them', [holesStayedHoles, mappedHoles.length], [true, 3]);
test('Array.from visits all three positions, holes included', [filled, blankIsUndefined], [[0, 1, 2], true]);
test('it copies any iterable, so a Set is how you deduplicate', unique, ['garri', 'rice', 'beans']);
test('a string is iterable by code point, not by UTF-16 unit', unitsAgainstPoints, [4, 2]);
test('and mapping while copying saves building the array twice', [shouted.join(''), labels], ['IKEJA', ['garri:12', 'rice:4']]);
test('an array-like needs only a length; missing indices arrive as undefined', fromArrayLike, ['Lagos', 'gap', 'Kano']);
Array.from(iterable, fn) is a copy and a map in one pass, so it never builds the intermediate array that [...thing].map(fn) does. With { length: n } as the source it becomes the range constructor JavaScript never shipped, which is where most of its use lives: Array.from({ length: 12 }, (_, i) => i + 1).
The hole story is the reason it exists. new Array(3) is length three with no elements, and map, forEach, filter and reduce all skip holes, so new Array(3).map((_, i) => i) returns three holes and looks broken. Array.from reads indices 0..length-1 directly, so every position is visited. Array(3).fill(0) is the other way out.
It also bridges two gaps that [...spread] cannot. Spread demands an iterable, so an array-like — a { length } object, or older DOM collections — goes through Array.from instead. And on a string it splits by code point, so a flag or an emoji stays whole where split('') and .length cut it in half.