2

Getting error arr.reduce is not a function for multidimensional arrays - works fine for simple arrays - not sure what's going wrong?

let arr = [4, [5, 7]]
let sum = 0

const calculateSum = (arr) => {
  return arr.reduce(function(acc, currentVal) {
    const isEntryArray = Array.isArray(currentVal)
    if (isEntryArray) {
      acc= acc + calculateSum(currentVal)
    } else {
      acc = acc + currentVal
    }
    return acc
  }, 0)
}
console.log(calculateSum(arr))
console.log(sum) ```

1
  • Running this in the browser console doesn't give an error... perhaps your last edit fixed it? Commented Dec 24, 2022 at 5:15

2 Answers 2

3

Instead of using a recursive function flatten the array and then use reduce to calculate the sum.

const arr = [4, [5, 7, [12, [1, 2]]]];

function calculateSum(arr) {
  return arr.flat(Infinity).reduce(function (acc, c) {
    return acc + c;
  }, 0);
}

console.log(calculateSum(arr));

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

1 Comment

.flat(Infinity) is slick.
0

You are passing in a boolean not an array when you do:

acc= acc + calculateSum(isEntryArray)
                        // ^^^ from Array.isArray()

I believe what you wanted was to pass in the current sub array

acc= acc + calculateSum(currentVal)

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.