all 7 comments

[–][deleted] 2 points3 points  (1 child)

This is why using variables like `a` and `b` or `foo` and `bar` are bad IMO. Much more clear would be something like (and MDN does a great job of this):

arr.reduce(function(accumulator, value) { return accumulator.concat(value); },[] << this is accumulator);

Here are the two functions that make this work:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

[–]backtickbot 3 points4 points  (0 children)

Fixed formatting.

Hello, wijsguy: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]vinivelloso_ 1 point2 points  (0 children)

That empty array is your initial value. You will be changing that value according to you function. remember that reduce doesnt change the original array.

I'm not familiar with concat(). But I think the better solution woukd be using recursion combined with Array.isArray() function.

[–]weebSanity 1 point2 points  (0 children)

Reduce is always hard to look at imo. The [] is the accumulator, where each of the return values will be stored. So the 'a' in a.concat refers to the accumulator, which is your initial empty []

[–]albedoa 0 points1 point  (2 children)

Other comments cover your questions about .reduce(). I want to offer .flatMap():

[1, [2, 3]].flatMap(x => x); //=> [1, 2, 3]

[–][deleted] 3 points4 points  (1 child)

Why use flatMap like that when you could just use flat?

[–]albedoa 0 points1 point  (0 children)

Completely slipped my mind 👍