HomeToolsAbout a20k

flat

What is it

The depth level specifies how deep a nested array structure should be flattened.

  • Depth level defaults to 1
const merge = arrays.flat();

Returns/Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth

  • creates a deep copy
// default: single level const arr1 = [0, 1, 2, [3, 4]]; arr1.flat(); // [0, 1, 2, 3, 4]; // passed num of level const arr2 = [0, 1, [2, [3, [4, 5]]]]; arr2.flat(); // [0, 1, 2, [3, [4, 5]]]; arr2.flat(2); // [0, 1, 2, 3, [4, 5]]; // infinite level const arr3 = [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]; arr3.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9]; // redundancies are kept const arr4 = [1, 2, 2, 2, [3, 4]]; arr4.flat(); // [1, 2, 2, 2, 3, 4]; // Flat removes empty holes in arrays const arr5 = [1, 2, , 4, 5]; arr5.flat(); // [1, 2, 4, 5]

.flatMap()

combination of the map() and flat() methods

  • loops through the elements of an array and concatenates the elements into by one level
  • flatMap() takes in a callback function which takes in the current element of the original array as a parameter
const arr = [1, 2, [3, [4, 5, [6, 7]]]]; /* single level without calculation */ arr.flatMap((element) => element); // [1, 2, [4, 5, [6, 7]]]; /* single level with calculation */ arr.flatMap((element) => element * 2); // [2, 4, NaN]; /* flatten first before flatMap */ arr.flat(2).flatMap((element) => element * 2); // [2, 4, 6, 8, 10, NaN]

Alternatives

// using spread and concat const flatArray = [].concat(...array); // using reduce function flatten(arr) { return arr.reduce(function (flat, toFlatten) { return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); }, []); }
© VincentVanKoh