2

I have a array with 4 element. I want to get a new array which calculates the sum of array elements where number of opereands increases one at a time.

For example I have an array [1000, 2000, 2000, 4000]. Result array should be like

[ 1000, 1000 + 2000, 1000 + 2000 + 2000, 1000 + 2000 + 2000 + 4000]

i.e [1000, 3000, 5000, 9000]

var array = [1000, 2000, 2000, 4000];

var newArray = array.map((e,i) => e)

console.log(newArray);

Is there any way to do that using map function ? Or any other way ?

IamGrooot
  • 940
  • 1
  • 17
  • 44
  • var numbers1 = [1000, 2000, 2000, 4000]; var numbers2 = numbers1.map(myFunction) function myFunction(value, index, array) { var i= 0; while (index > i) { index--; value = value + array[index]; } return value ; } – Vikash sah Mar 11 '19 at 19:18

2 Answers2

3

    const array = [1000, 2000, 2000, 4000];
    const result = array.reduce((acc,item, index) => { 
      if (index === 0) { acc.push(item); }
      else {
        acc.push(acc[index-1] + item);
      }
      return acc;
    } ,[]);
    console.log(result);
Reza
  • 18,865
  • 13
  • 88
  • 163
1

Just loop through you original array and before you add the value to your new Array, add the last Value of the new Array to it.

var array = [1000, 2000, 2000, 4000];

var newArray = [];
for(n of array){
  if(newArray.length>0) newArray.push(newArray[newArray.length-1]+n)
  else newArray.push(n)
}

console.log(newArray);
moronator
  • 304
  • 4
  • 11