Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda