I want to convert this array, into one array as shown below. How can I accomplish this with a method that will work, regardless of the level of nesting in the array.
var array = [1, [2], [3, [[4]]]]
//Output = [1,2,3,4]
I want to convert this array, into one array as shown below. How can I accomplish this with a method that will work, regardless of the level of nesting in the array.
var array = [1, [2], [3, [[4]]]]
//Output = [1,2,3,4]
You can use recursive function for this.
var array = [1, [2], [3, [[4]]]];
function flatten(ar) {
var result = [];
ar.forEach(function(e) {
if (Array.isArray(e)) {
result = result.concat(flatten(e));
} else {
result.push(e);
}
})
return result;
}
console.log(flatten(array));
Make it recursive!
result = [];
function covert(array) {
for (var b in array) {
if (typeof b === number) {
result.push(b)
} else {
convert(b)
}
}
}