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));
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));
Share
Improve this question
asked Feb 8, 2019 at 2:41
totalnoobtotalnoob
2,74110 gold badges39 silver badges72 bronze badges
2
-
Is there a reason
Array.prototype.flat()
orArray.prototype.flatMap()
is not being used? – guest271314 Commented Feb 8, 2019 at 2:49 - 2 I'm learning how to use reduce. but good to know there is a native method – totalnoob Commented Feb 8, 2019 at 2:50
3 Answers
Reset to default 6The 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));
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));
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.