Javascript - updating array values by adding the previous value

Viewed 1287

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)

2 Answers

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)

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.

Related