Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of previous elements from an array in Javascript

I have a javascript array with these values:

fbDivHeightsTest = [280,430,408,430,408] 

I need a new array with the sum of elements like this:

newArray = [280, 710, 1118, 1548, 1956]. 

The fbDivHeightsTest[0] + fbDivHeightsTest[1], fbDivHeightsTest[0] + fbDivHeightsTest[1] + fbDivHeightsTest[2] and so on.

I have tried like this, but the reduce function is not returning the result I expect. It returns: 280, 710, 1398, 2818, 5614

sectionsSeclector.each(function(index, item) {    
    var sum = fbDivHeights.reduce(function(a, b) { return a + b; }, 0);
    fbDivHeights.push( $(item).outerHeight() + sum);       
});  

Can you please help me with this? thanks!

like image 902
Orsi Avatar asked Nov 03 '17 11:11

Orsi


2 Answers

You can use reduce method in combination with map method.

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

let array = [280,430,408,430,408];
array = array.map((elem, index) => array.slice(0,index + 1).reduce((a, b) => a + b));
console.log(array);

You can also use only map method.

let array = [280,430,408,430,408],sum;
array = array.map(elem => sum = (sum || 0) + elem);
console.log(array);
like image 60
Mihai Alexandru-Ionut Avatar answered Nov 09 '22 23:11

Mihai Alexandru-Ionut


You could use a closure over the actual sum and map the incremented result.

How it works:

Assuming the function is called, then

(s => a => s += a)(0)
//                 ^  value for s

it returns

a => s += a      // s = 0

for the callback of Array#map and for every loop,

280 => s += 280  // s =  280
430 => s += 430  // s =  710
408 => s += 408  // s = 1118
430 => s += 430  // s = 1548
408 => s += 408  // s = 1956

var array =[280, 430, 408, 430, 408],
    result = array.map((s => a => s += a)(0));
    
console.log(result);
like image 43
Nina Scholz Avatar answered Nov 10 '22 01:11

Nina Scholz