Extract numbers from a n-dimensional array in javascript

Viewed 39

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?

2 Answers

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

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.

Related