ttmt
ttmt

Reputation: 4984

Javascript - updating array values by adding the previous value

I have an array like

arr=[20, 40, 40, 40] and I want to update it toarr=[20, 60, 100, 140]

I don't want to update the first value but the following values should be that value plus the value before it in the array

I sort of have it working here but it has to add the previous value after its updated from the previous loop and I'm having to add the first value separately at the end.

let arr = [20, 40, 40, 40]

let arrUpdate = []

for(let n=0; n<arr.length; n++){
  arrUpdate.push(arr[n] + (arr[n-1]))
}

arrUpdate[0] = arr[0]

console.log(arrUpdate)

Upvotes: 2

Views: 2250

Answers (2)

Akrion
Akrion

Reputation: 18515

You could also use Array.reduce:

let arr = [20, 40, 40, 40]

let result = arr.reduce((r,c,i) => (r.push(i ? c + r[i-1] : c), r), [])

console.log(result)

And get the running sum from the previous element in the accumulator.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386634

You could map new sums by taking a sum variable with a starting value of zero.

let arr = [20, 40, 40, 40],
    sum = 0,
    result = arr.map(v => sum += v);

console.log(result)

Upvotes: 4

Related Questions