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

203
Vistas
forEach returning undefined

This function goes through the arrays and in each object, add the 1st number and subtract the 2nd number

eg. number([[10,0],[3,5],[5,8]]) = (10-0) + (3-5) + (5-8) Total should equal 5

Problem: I'm using a forEach loop but it returns undefined, when I console.log the number shows 5.

var number = function(busStops){
  var total = 0;
  busStops.forEach(function(n){
    total = total + n[0] - n[1];
    return total;
  })
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could reduce the array.

const
    number = busStops => busStops.reduce((t, [a, b]) => t + a - b, 0);

console.log(number([[10, 0], [3, 5], [5, 8]]));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Just found the issue, the return should be outside the forEach loop

var number = function(busStops){
  var total = 0;
  busStops.forEach(function(n){
    total = total + n[0] - n[1];
  })
  return total;
}
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