_.flattenDeep

Recursively flattens array.

  1. // Underscore/Lodash
  2. _.flattenDeep([1, [2, [3, [4]], 5]]);
  3. // => [1, 2, 3, 4, 5]
  4.  
  5. // Native
  6. const flattenDeep = (arr) => Array.isArray(arr)
  7. ? arr.reduce( (a, b) => a.concat(flattenDeep(b)) , [])
  8. : [arr]
  9.  
  10. flattenDeep([1, [[2], [3, [4]], 5]])
  11. // => [1, 2, 3, 4, 5]
  12.  
  13. // Native(ES2019)
  14. [1, [2, [3, [4]], 5]].flat(Infinity)
  15. // => [1, 2, 3, 4, 5]

Browser Support

ChromeEdgeFirefoxIEOperaSafari
46.0 ✔16.0 ✔37.0 ✔7.1 ✔

Browser Support for Array.prototype.flat()

ChromeEdgeFirefoxIEOperaSafari
69 ✔62 ✔56 ✔12 ✔