home

flat

The flat() method creates a new array with all sub-array elements recursively flattened up to the specified depth. It's useful for simplifying nested arrays into a single-level array — or flattening deeply nested structures with Infinity.

This example provides a custom implementation of Array.prototype.flat(), supporting variable depth.

Array.prototype.customFlat = function (depth = 1) {
  const result = [];
 
  const flatten = (array, depth) => {
    for (const item of array) {
      if (Array.isArray(item) && depth > 0) {
        flatten(item, depth - 1);
      } else {
        result.push(item);
      }
    }
  };
  flatten(this, depth);
 
  return result;
};
 
const arr = [0, 1, [2, [3, [4, 5]]]];
console.log(arr.customFlat());
// [0, 1, 2, [3, [4, 5]]]
console.log(arr.customFlat(2));
// [0, 1, 2, 3, [4, 5]]
console.log(arr.customFlat(Infinity));
// [0, 1, 2, 3, 4, 5]