Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!