Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Obtain Cumulative Sum Array Using Underscore.js?

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.

like image 974
user664023 Avatar asked Aug 09 '12 19:08

user664023


People also ask

How do you sum cumulative in JavaScript?

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.

How do you use underscore in JavaScript?

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.


1 Answers

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, []);
}
like image 197
Sebastian Paaske Tørholm Avatar answered Nov 10 '22 09:11

Sebastian Paaske Tørholm