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

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

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 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!