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

156
Vistas
Accumulate values in array without reducing into single value

I want to do something really similar to reduce with values in my array, but I do not want to sum it all up into one value. I want to carry on the summed up value and insert the increment into each consecutive value in the array.

Like this:

const array = [{ number: 6, value: 10 }, { number: 5, value: 12 }, { number: 2, value: 5 }]

// Do something like this
const newArray = array.reduce((accumulated, item) => {
  return {  
    number: (100 / item.number) + accumulated.value || 0,
    value: ((100 / item.number) + accumulated.value || 0) * item.value
  }
}, 0)

// But the result should be something like this
newArray = [{ number: 6, value: 10 }, { number: 30, value: 360 }, { ...and so on }]

How can this be achieved? ES6 with/without lodash preferred.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Since the input and output items are one-to-one, I think using .map would be more intuitive than .reduce - you can keep an outside variable for the last object returned.

const array = [{ number: 6, value: 10 }, { number: 5, value: 12 }, { number: 2, value: 5 }]

let lastReturn = array.shift();
const newArray = [lastReturn].concat(array.map(({ number, value }) => {
  const newObj = {  
    number: (100 / number) + lastReturn.value || 0,
    value: ((100 / number) + lastReturn.value || 0) * value
  };
  lastReturn = newObj;
  return newObj;
}));
console.log(newArray);

While it'd be technically possible to use .reduce for this (you can use .reduce to achieve anything related to array iteration, .map makes more sense here.

about 4 years ago · Santiago Gelvez 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