Creating an array of cumulative sum in javascript

后端 未结 21 1602
时光取名叫无心
时光取名叫无心 2020-11-27 06:23

This is an example of what I need to do:

var myarray = [5, 10, 3, 2];

var result1 = myarray[0];
var result2 = myarray[1] + myarray[0];
var result3 = myarray         


        
21条回答
  •  旧巷少年郎
    2020-11-27 07:01

    A more generic (and efficient) solution:

    Array.prototype.accumulate = function(fn) {
        var r = [this[0]];
        for (var i = 1; i < this.length; i++)
            r.push(fn(r[i - 1], this[i]));
        return r;
    }
    

    or

    Array.prototype.accumulate = function(fn) {
        var r = [this[0]];
        this.reduce(function(a, b) {
            return r[r.length] = fn(a, b);
        });
        return r;
    }
    

    and then

    r = [5, 10, 3, 2].accumulate(function(x, y) { return x + y })
    

提交回复
热议问题