I'm getting a little confused with using reduce.
it's array.reduce((accumulator, value) => do something with accumulator, why is this returning back an empty array?
let a = [
[1,2],
[
[3,4]
],
[
[[5],[6]]
]
];
const flatten = arr => arr.reduce((a, v) => {
v instanceof Array ? flatten(v) : a.push(v);
return a;
}, [])
console.log(flatten(a));
3 Answers 3
The flatten(v) returns an array, but you're not doing anything with it currently. Try pushing the spread array into the accumulator instead:
let a = [
[1,2],
[
[3,4]
],
[
[[5],[6]]
]
];
const flatten = arr => arr.reduce((a, v) => {
v instanceof Array ? a.push(...flatten(v)) : a.push(v);
return a;
}, [])
console.log(flatten(a));
Or, you can use concat, and only use the conditional operator when you need the entire thing to resolve to an expression (don't use it as an alternative to if/else):
let a = [
[1,2],
[
[3,4]
],
[
[[5],[6]]
]
];
const flatten = arr => arr.reduce((a, v) => {
if (v instanceof Array) {
return a.concat(flatten(v))
} else {
a.push(v);
return a;
}
}, [])
console.log(flatten(a));
2 Comments
let arr = [[1,2],[[3,4]],[[[5],[6]]]];
const flattenArr = (arr) =>
arr.reduce((acc, val) =>
Array.isArray(val) ?
acc.concat(flattenArr(val)) :
acc.concat(val), []);
console.log(flattenArr(arr));
Comments
let array = [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20, 22]]
const flatten = array.reduce((a, b) => {
return a.concat(b)
})
console.log(flatten)
.concat concatenates two arrays, reduce does a loop under the hood and concatenation results in flattening.
Array.prototype.flat()orArray.prototype.flatMap()is not being used?