EasyArrays📖 Theory Question

How do Array.flat() and Array.flatMap() work?

💡

Hint

flat() flattens nested arrays; flatMap() maps then flattens one level — more efficient

Full Answer

const nested = [1, [2, [3, [4]]]];

nested.flat();         // [1, 2, [3, [4]]] — default depth 1
nested.flat(2);        // [1, 2, 3, [4]]
nested.flat(Infinity); // [1, 2, 3, 4] — fully flat

// flatMap = map + flat(1) — more efficient than separate calls
const sentences = ['Hello World', 'Foo Bar'];
sentences.flatMap(s => s.split(' ')); // ['Hello', 'World', 'Foo', 'Bar']

// vs two-step (less efficient)
sentences.map(s => s.split(' ')).flat(); // same result

// flatMap can filter + transform in one pass
const nums = [1, 2, 3, 4, 5];
nums.flatMap(n => n % 2 === 0 ? [n, n * 10] : []);
// [2, 20, 4, 40] — odds removed, evens doubled
// Return [] to skip, [val] to keep, [a, b] to expand one item into two
💡 flatMap is more efficient than map+flat because it only iterates once. Use it as a combined filter+map by returning [] to skip items.

More Arrays Questions

EasyWhen would you use map vs forEach vs reduce vs filter?EasyHow do Array.find(), findIndex(), some(), and every() work?EasyWhat are immutable array operations and the new ES2023 methods?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint