1

Input array: [1, 2, [3, 4, [5, 6, [7, 8, [9]]]], 10]
Output array: [1,2,3,4,5,6,7,8, 9, 10]

Is there a way to get the output array without using multiple loops?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    Tips: [flat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) – Simone Rossaini Sep 21 '22 at 09:58
  • Does this answer your question? [Extracting common numbers from multi-dimensional array](https://stackoverflow.com/questions/73061492/extracting-common-numbers-from-multi-dimensional-array) – Nazeer Shaik Sep 21 '22 at 10:01
  • @NazeerShaik I do not see any relevance that question has to this one – VLAZ Sep 21 '22 at 10:02
  • 1
    If your JS has no Array flat method, `const flat=v=>(!Array.isArray(v))?v:v.reduce((a,v)=>a.concat(flat(v)), []);` – Jaromanda X Sep 21 '22 at 10:06

2 Answers2

7

You can add an infinity argument to flat to get all the numbers from the many nested arrays.

const data = [1, 2, [3, 4, [5, 6, [7, 8, [9]]]], 10];
const out = data.flat(Infinity);
console.log(out);
Andy
  • 61,948
  • 13
  • 68
  • 95
1
console.log([1, 2, [3, 4, [5, 6, [7, 8, [9]]]], 10].flat(Infinity));

Use 'flat' method to flatten the array. Or you can also use underscore module method.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
KITISH
  • 18
  • 3