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

167
Vistas
How loop through array.reduce()?

I have array contains 300elements []; and I want to sum each [I],


for(var i = 0; i<300; i++){
var array2 = arr[i].reduce((prev, next) => (
return prev + next
))
}

it should like that array1 = [1,2,3,4,5,6,7,8,9..] array2 [3,6,10...]

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

var arr = [1,2,3,4,5,6,7,8,9,10,.....]
var array2 = []
// Log to console
for(var i = 1; i<300; i++){
  var newArray = arr.slice(0, i+1).reduce((prev, next) => {
    return prev + next
   })
   array2.push(newArray)

}
console.log(array2)

array2 output : [3, 6, 10, 15, 21, 28, 36, 45, 55...]


In your code

this causes an error for two reasons

var array2 = arr[i].reduce((prev, next) => (
return prev + next
))

the reduce() method is for arrays only and arr[i] would output a number. Instead you were looking to use the slice() method.

And to use return you must use curly braces {} instead of (). Alternatively you could've done arr.slice(0, i+1).reduce((prev, next) => prev + next). (see: When should I use a return statement in ES6 arrow functions)

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