I want to get numbers from
var arr = [1,[2],[[3]],[[[4]]]];
using JavaScript/jQuery.
could be more in the series.
I want to get numbers from
var arr = [1,[2],[[3]],[[[4]]]];
using JavaScript/jQuery.
could be more in the series.
You are looking for Array.prototype.reduce()
For example:
var arr = [1,[2],[[3]],[[[4]]]];
const flatten = arr => arr.reduce(
(acc, val) => acc.concat(
Array.isArray(val) ? flatten(val) : val
),
[]
);
console.log(flatten(arr));
Realistically, if you only want to get the numbers you can just convert the array to a string then use a simple regex to extract all of the numbers:
console.log([1,[2],[[3]],[[[4]]]].toString().match(/\d+/g)); // ["1","2","3","4"]
If the result must be an array of numbers (not strings), you can use Array#map
to run the conversion (e => +e
).
console.log([1,[2],[[3]],[[[4]]]].toString().match(/\d+/g).map(e => +e)); // [1,2,3,4]