Skip to content

Latest commit

 

History

History
33 lines (28 loc) · 1.26 KB

deepFlatten.md

File metadata and controls

33 lines (28 loc) · 1.26 KB
title tags author_title author_url author_image_url description image
deepFlatten
array,recursion,intermediate
Deepak Vishwakarma
Implementation of "deepFlatten" in typescript, javascript and deno.

TS JS Deno

Deep flattens an array.

Use recursion.[polyfill for Array.prototype.flat] Use Array.prototype.concat() with an empty array ([]) and the spread operator (...) to flatten an array. Recursively flatten each element that is an array.

const deepFlatten = (arr: any[]): any[] => {
  if (typeof Array.prototype.flat !== "undefined") return arr.flat(Infinity);
  return [].concat(
    ...arr.map((v: any) => (Array.isArray(v) ? deepFlatten(v) : v))
  );
};
deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]
deepFlatten([1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]