Creating an array of cumulative sum in javascript

后端 未结 21 1638
时光取名叫无心
时光取名叫无心 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:04

    My initial ES6 thought was similar to a few above answers by Taeho and others.

    const cumulativeSum = ([head, ...tail]) =>
       tail.reduce((acc, x, index) => {
          acc.push(acc[index] + x);
          return acc
      }, [head])
    console.log(cumulativeSum([-1,2,3])
    

    The solution performs:

    n lookups, n - 1 sums and 0 conditional evaluations

    Most of what I saw above appeared to use:

    n lookups, 2n sums, and n conditional evaluations:

    You could do this with ie6 safe js as well. This is possibly more efficient since you don't have to create the tail spread array.

    function cumulativeSum(a) {
        var result = [a[0]];
        var last = a[0];
        for (i = 1; i < a.length; i++) {
            last = last + a[i];
            result.push(last)
        }
        return result;
    }
    console.log(cumulativeSum([-1,2,3]))
    

提交回复
热议问题