JavaScriptFundamental (ES6), part 1
Flatten deeply with flat(Infinity) in JavaScript
73 flat, flatMap and the depth you forgot to pass
fairFlatten a nested list of market takings with flat, then again with an explicit depth and with Infinity. Use flatMap to expand one order into several receipt lines and to filter and map in a single pass. Then show the two things flat does that surprise people: it removes holes, and it leaves strings alone.
Stuck? Three hints, smallest first
- 1.
flat()defaults to depth 1, which is one level, not all of them. - 2.
flatMap(fn)ismap(fn).flat()— depth one, always, no matter what you pass. - 3. Returning
[]from aflatMapcallback contributes nothing, which is how one pass can both drop and expand.
const takings = [[4500, 12000], [8000], [[3000, 1000], 500]];
const oneLevel = takings.flat();
const twoLevels = takings.flat(2);
const allLevels = takings.flat(Infinity);
const totalOfAll = allLevels.reduce((a, b) => a + b, 0);
const orders = [
{ item: 'garri', qty: 2, kobo: 45000 },
{ item: 'rice', qty: 0, kobo: 450000 },
{ item: 'beans', qty: 3, kobo: 30000 },
];
const lines = orders.flatMap(({ item, qty }) => Array.from({ length: qty }, (_, i) => `${item} #${i + 1}`));
const priced = orders.flatMap(({ item, qty, kobo }) => (qty === 0 ? [] : [`${item}=${(qty * kobo) / 100}`]));
const withIndex = orders.flatMap(({ item }, i) => [i, item]);
const stillNested = [1, 2].flatMap((n) => [[n * 10]]);
const sparse = [1, , 3];
const sparseFlat = sparse.flat();
const strings = [['a'], 'bc', ['d']].flat();
const flatOfFlat = [[[1]]].flat().flat();
console.log('flat :', oneLevel);
console.log('depths :', twoLevels, allLevels, totalOfAll);
console.log('lines :', lines, '| priced:', priced);
console.log('sparse :', sparse.length, sparseFlat, '| strings:', strings);
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('flat with no argument goes exactly one level down', oneLevel, [4500, 12000, 8000, [3000, 1000], 500]);
test('a depth of 2 reaches the next one, and Infinity reaches the bottom', [twoLevels, allLevels], [[4500, 12000, 8000, 3000, 1000, 500], [4500, 12000, 8000, 3000, 1000, 500]]);
test('which is what makes a sum over ragged data a one-liner', totalOfAll, 29000);
test('flatMap expands one item into several', lines, ['garri #1', 'garri #2', 'beans #1', 'beans #2', 'beans #3']);
test('and returning an empty array drops an item, so filter and map fit in one pass', priced, ['garri=900', 'beans=900']);
test('the callback still gets the index', withIndex, [0, 'garri', 1, 'rice', 2, 'beans']);
test('flatMap flattens one level and only one, whatever you return', stillNested, [[10], [20]]);
test('flat drops holes, so the length changes even with nothing nested', [sparse.length, sparseFlat], [3, [1, 3]]);
test('a string is not flattened, and two flats are not the same as flat(2) on deeper data', [strings, flatOfFlat], [['a', 'bc', 'd'], [1]]);
flat's default depth of one is the whole trap. Data that came back three levels deep looks half-fixed after flat(), and the bug appears later as an array where a number was expected. If you genuinely do not know the shape, say flat(Infinity) and mean it.
flatMap is the useful one. Expanding an item into many, dropping an item by returning [], and mapping normally by returning a single-element array are all the same call, which turns a filter plus a map plus a concat into one traversal. It always flattens exactly one level, so a callback that returns nested arrays keeps the nesting.
The hole behaviour is worth remembering because it is the only cheap way to remove them: [1, , 3].flat() is [1, 3], length two, where the original had length three. And strings, though iterable, are never flattened — flat checks for arrays, not for iterables, so 'bc' stays a single item rather than becoming two characters.