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!
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With