I am trying to spread the inner array elements of an array but couldn't figure it out how it works.
Input:
[1,2,[3,4],[5,6]]
Output:
[1,2,3,4,5,6]
How do I convert the first array into 2nd one?
I am trying to spread the inner array elements of an array but couldn't figure it out how it works.
Input:
[1,2,[3,4],[5,6]]
Output:
[1,2,3,4,5,6]
How do I convert the first array into 2nd one?
var array = [1,2,[3,4],[5,6]];
var newArray = [].concat(...array);
console.log(newArray); // [1, 2, 3, 4, 5, 6]
You could take a generator for the array which checks the lement and for arrays, it returns the nested elements.
function* flat() {
var i = 0;
while (i < this.length) {
if (Array.isArray(this[i])) {
this[i][Symbol.iterator] = flat;
yield* this[i];
} else {
yield this[i];
}
i++;
}
}
var array = [1, 2, [3, 4], [5, 6], [7, [8, 9]]];
array[Symbol.iterator] = flat;
console.log([...array]);
The term is "flattening" - here's a simple one-level flattening function:
const arr = [1, 2, [3, 4], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(curr), []);
console.log(flatten(arr));
.as-console-wrapper { max-height: 100% !important; top: auto; }
Deeply nested arrays require a different approach - here's a recursive function:
const arr = [1, 2, [3, 4, "a", ["b", "c"]], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(Array.isArray(curr) ? flatten(curr) : curr), []);
console.log(flatten(arr));
.as-console-wrapper { max-height: 100% !important; top: auto; }