flatten a nested array

ES6, JavaScript, Array

Convert a multi-dimensional array into a single-level array using the flat() method.

Explanation

  • arr.flat(): This method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth (default depth is 1).
  • arr.flat(Infinity): Using Infinity as the depth parameter flattens the array completely, regardless of how deeply nested it is.
  • arr.flatMap(): This method first maps each element using a mapping function, then flattens the result into a new array.

Usage

To flatten a nested array, use the following methods:

// Shallow flatten (one level deep)
const nestedArray = [1, [2, 3], [4, [5, 6]]];
const shallowFlat = nestedArray.flat();
console.log(shallowFlat);
// Expected output: [1, 2, 3, 4, [5, 6]]

// Deep flatten (all levels)
const deeplyNested = [1, [2, [3, [4, 5]]]];
const deepFlat = deeplyNested.flat(Infinity);
console.log(deepFlat);
// Expected output: [1, 2, 3, 4, 5]

// Using flatMap for transformation and flattening
const words = ['hello world', 'foo bar'];
const allWords = words.flatMap(str => str.split(' '));
console.log(allWords);
// Expected output: ['hello', 'world', 'foo', 'bar']