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

123
Views
Recursion - sum of array

i have reviewed the other posts on stack overflow, and as mentioned I am trying to find the sum of an array using recursion and if its all numbers i.e [2, 6, 11, 4, 13, 5] it works fine but if in the array there are letters i.e["a","b","c"] it adds a 0 to the end giving "abc0" taking off the 0 after the return returns abcundefined instead of return 0 i tried return array, which works for the ["a","b","c"] version but in [2, 6, 11, 4, 13, 5] returns it concat rather than addition. thanks in advance for your time and help. =)

function calculateSumRecursion(array) {
  console.log(array)
  if(array.length === 0 ) return 0
  return array[0]+calculateSumRecursion(array.slice(1))
  
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you think that, you can stop if there is one element.

function calculateSumRecursion(array) {
  // just to improve the basic logic, there can be other cases which can be handled i.e. if the array is empty.
  if ( array.length === 1 ) array[0]
  return array[0] + calculateSumRecursion( array.slice(1) )
}
about 4 years ago · Juan Pablo Isaza Report

0

You could solve this by simply changing the stop condition to 1 element.

function calculateSumRecursion(array) {
  if (array.length < 1) throw "Can't calculate a sum of empty array";
  if (array.length === 1) return array[0]
  return array[0] + calculateSumRecursion(array.slice(1))
}

array = [1, 2, 3, 4, 5, 6]
console.log(calculateSumRecursion(array))


array = ["a", "b", "c", "d", "e"]
console.log(calculateSumRecursion(array))

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!