Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Reduce giving errors for multidimensional array sum js

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(isEntryArray)
    } else {
      acc = acc + currentVal
    }
    return acc
  }, 0)
}
console.log(calculateSum(arr))
console.log(sum) ```

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!