Search This Blog

2023/09/10

Javascript:Flatten Array to single depth

Sample Input:
const numbers = [
1,
[3, [2, 8, [12, 9]]],
[5],
[12, [[5]]],
[100, [23, 45]]
]

Sample Output:
const numnbers = [
1, 3, 2, 8, 12,
9, 5, 12, 5, 100,
23, 45
]

Solution(1st Method):
const numbers = [
1,
[3, [2, 8, [12, 9]]],
[5],
[12, [[5]]],
[100, [23, 45]]
]

function flattenNextedArray(arr) {
let numbers = [];

for (let elt of arr) {
if (Array.isArray(elt)) {
numbers = numbers.concat(flattenNextedArray(elt))
} else {
numbers.push(elt)
}
}
return numbers
}


var flatten = flattenNextedArray(numbers)
console.log(flatten)

Solution(2nd Method):
const numbers = [
1,
[3, [2, 8, [12, 9]]],
[5],
[12, [[5]]],
[100, [23, 45]]
]

var flatten = numbers.flat(Infinity)
console.log(flatten)

No comments:

Post a Comment