5

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));

2
  • Is there a reason Array.prototype.flat() or Array.prototype.flatMap() is not being used? Commented Feb 8, 2019 at 2:49
  • 2
    I'm learning how to use reduce. but good to know there is a native method Commented Feb 8, 2019 at 2:50

3 Answers 3

7

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));

Sign up to request clarification or add additional context in comments.

2 Comments

ahh. so pushing to the accumulator has to all happen in the same loop
Either that, or pass the accumulator array around to each recursive call
0

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

0

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.

1 Comment

Please read How do I write a good answer?. While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.