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

89
Vistas
Returning previous and current index sum while mapping through array?

I have an array such as this:

[
 {
  id: 1,
  amount: 100
 },
 {
  id: 2,
  amount: -50
 },
 {
  id: 3,
  amount: 30
 }
]

How can I retrieve an array where the amount would be the sum of the previous index sum? For example if the starting amount is 0, I would like to retrieve this array:

[100, 50, 80] // 0 + 100 = 100, then 100 - 50 = 50, then 50 + 30 = 80
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could use accumulator param from the reduce with index - 1 to get the latest value added.

const data = [{"id":1,"amount":100},{"id":2,"amount":-50},{"id":3,"amount":30}]

const result = data.reduce((r, { amount }, i) => {
  r.push((r[i - 1] || 0) + amount)
  return r
}, [])

console.log(result)

You can also use map and thisArg argument.

const data = [{"id":1,"amount":100},{"id":2,"amount":-50},{"id":3,"amount":30}]

const result = data.map(function({ amount }, i) {
  return (this.last = (this.last || 0) + amount)
}, {})

console.log(result)

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