Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda