I have an array = [1,2,3,4,5]
and would like to obtain the cumulative sum array using underscore.js.
The result I want is:
[1,3,6,10,15]
I want the array not the cumulative sum 15 as a value. Any help would be appreciated.
cumulativeSum is the function value => sum += value , with sum initialized to zero. Every time it's called, sum is updated and will equal the previous value (output[n-1]) when called the next time (with input[n]). Note that sum will need to be set to zero explicitly when you want to reuse the summation.
Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.
You can do a _.reduce()
to get this:
_.reduce([1, 2, 3, 4, 5], function (acc, n) { acc.push( (acc.length > 0 ? acc[acc.length-1] : 0) + n); return acc }, [])
A more readable version goes here:
var prefixSum = function (arr) {
var builder = function (acc, n) {
var lastNum = acc.length > 0 ? acc[acc.length-1] : 0;
acc.push(lastNum + n);
return acc;
};
return _.reduce(arr, builder, []);
}
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