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

  1. 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
  2. Flatten and map in one step: javascript const sentences = ["hello world", "foo bar"]; const words = sentences.flatMap(s => s.split(" ")); // ["hello", "world", "foo", "bar"]
  3. 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

  • flatMap is more efficient than map followed by flat(1).
  • For deep flattening of arbitrary depth, Infinity is convenient but check performance on huge datasets.

Common issues

  • flat creates a new array but shallow copies elements; nested objects are still shared.
  • Forgetting to handle empty arrays in reduce-based grouping leads to undefined keys.