How To Obtain Cumulative Sum Array Using Underscore.js?

underscore.js

Solution

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, []);
}

Problem

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.

Original source