简体   繁体   中英

How to calculate the sum of each element of an array and its previous elements in JavaScript?

For example, if I have an array [1,2,3,4], I want to calculate 1+2, 1+2+3 and 1+2+3+4 and return a new array. How can I do that?

let arr = [1, 2, 3, 4];

doSomething(arr);

output...

newArr = [1, 3, 6, 10];

You could slice the array for getting the wanted elements and reduce the value for getting a sum.

Methods:

 var array = [1, 2, 3, 4], sums = array.map((_, i, a) => a.slice(0, i + 1).reduce((a, b) => a + b)); console.log(sums);

Fun with a closure over the sum

 var array = [1, 2, 3, 4], sums = array.map((a => b => a += b)(0)); console.log(sums);

Add this function.

function dosomething (arr) {
  var i;
  if(i === 1 || i === 0) return arr; 
  for(i = 1; i<arr.length; i++){
    arr[i] += arr[i-1];
  }
  return arr;
}

You can try to use array.reduce

 let arr = [1, 2, 3, 4]; let newArr = []; arr.reduce((prev, current) => {newArr.push(prev+current); return prev + current}, 0); console.log(newArr);

Some elegant method:

 function getArrSum(arr) { if(!arr.length) return []; let tmp=[arr[0]]; for(let i=1; i<arr.length; i++) { tmp.push(tmp[i-1]+arr[i]); } return tmp; } let arr=[1,2,3,4]; console.log(getArrSum(arr));

 var a = [1,2,3,4];
 var b=[];

for(i=0;i<a.length;i++)
{   

  var sum = 0;

  for(j=0;j<=i+1;j++)
  {
    if(a[j] != null)
        sum=sum+a[j];
  }    
  b[i]=sum;
}

Fist of all I would like to share a link which shows what should be a good question. https://stackoverflow.com/help/how-to-ask

and about the calculation of the array is :

 function getArray(numbers) { if(!numbers.length) return []; let array=[numbers[0]]; for(let i=1; i < numbers.length; i++) { array.push(array[i-1]+numbers[i]); } return array; } let array=[1,2,3,4]; let procArray = []; console.log(getArray(array));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM