-2

Consider an array

a = [-4,58,9,,-91]

So I want to add these element in such way that my result will be b= [-4 ,(58-4 = 54), (54+9=63),(63-91=-28) ] so my array result is [-4,54,63,-28].

Any solution?

Tushar
  • 85,780
  • 21
  • 159
  • 179
vedika shrivas
  • 333
  • 2
  • 6
  • 14

1 Answers1

2

To modify your array in place, you can use a forEach loop:

const a = [-4,58,9,-91];
a.forEach((elt, i, arr) => {
  if (i > 0) {
    arr[i] = elt + arr[i - 1];
  }
});

console.log(a); // [-4,54,63,-28]
klugjo
  • 19,422
  • 8
  • 57
  • 75