How to flatten and manipulate nested arrays in JavaScript
· Category: JavaScript
Short answer
Use flat and flatMap to flatten nested arrays, and combine reduce with other methods to group, partition, or reshape complex data structures.
Steps
- Flatten arrays:
javascript const nested = [1, [2, 3], [4, [5]]]; nested.flat(); // [1, 2, 3, 4, [5]] nested.flat(2); // [1, 2, 3, 4, 5] nested.flat(Infinity); // fully flat - Flatten and map in one step:
javascript const sentences = ["hello world", "foo bar"]; const words = sentences.flatMap(s => s.split(" ")); // ["hello", "world", "foo", "bar"] - Group elements by key:
javascript const grouped = items.reduce((acc, item) => { const key = item.category; acc[key] = acc[key] || []; acc[key].push(item); return acc; }, {});
Tips
flatMapis more efficient thanmapfollowed byflat(1).- For deep flattening of arbitrary depth,
Infinityis convenient but check performance on huge datasets.
Common issues
flatcreates a new array but shallow copies elements; nested objects are still shared.- Forgetting to handle empty arrays in reduce-based grouping leads to
undefinedkeys.