1

I wanted to do a recursive function in order to add an array.

Here's the sample array I'm trying to use: [[[1, 2, [[3], 4]], 5, []]]

Since I'm learning, I wanted to try it with reduce... And it's working great, sometimes:

const sumItems = function(array) {
  return array.reduce(function(acc, x) {
    return acc + (Array.isArray(x) ? sumItems(x) : x);
  },0);
};

The thing is, I would've loved to be able to shorten it... Something like so:

const sumItems = function(array) {
  const reducer = (acc, x) => (acc || 0) + (Array.isArray(x) ? sumItems(x) : x);
  return array.reduce(reducer);
};

But that's not working at all... I'm not sure why and although I've been playing around with my code, console logging it etc etc etc, the best I can get is an output like this:

[ [ 1, 2, [ [Array], 4 ] ], 5, [] ]

Which I find really interesting...

Does someone knows how I could resolve this? Am I doing something wrong that I'm not yet aware of, regarding JavaScript?

Thank you for your time

2
  • Mention the initial value as 0 in your array.reduce() function like return array.reduce(reducer,0); and it will work as your expectations. Commented Jun 28, 2019 at 18:46
  • Thank you so much, both of you. I wish I could check both answers to give you credit, they were both quite enlightening. Commented Jun 28, 2019 at 18:48

2 Answers 2

3

You need to set initial value in reduce method otherwise if the first element is an array then it will fail and returns NaN in some iteration and next iteration acc || 0 will results 0 since NaN is falsy value.

var data = [
  [
    [1, 2, [
      [3], 4
    ]], 5, []
  ]
]

const sumItems = function(array) {
  const reducer = (acc, x) => acc + (Array.isArray(x) ? sumItems(x) : x);
  // -now || is not needed --^^^^----- since we'd added initial value so it will be always a number
  // for treating non-digit or non-array value you can replace `x` with `+x || 0` for treating it as `0`
  
  return array.reduce(reducer, 0);
  // ---- initial value-------^^^----
};

console.log(sumItems(data))

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

Comments

3

You are no longer passing an initial value to reduce. Do that instead of trying to || 0 the acc inside the reducer function.

const reducer = (acc, x) => acc + (Array.isArray(x) ? sumItems(x) : x);
const sumItems = array => array.reduce(reducer, 0);
//                                              ^

Without an initial value, reduce fails on empty arrays.

Comments

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.