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 ?

1
  • 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 ; } Commented Mar 11, 2019 at 19:18

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.