Search code examples
javascriptnested-lists

Extract numbers from a n-dimensional array in javascript


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?


Solution

  • 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);