Creating an array of cumulative sum in javascript

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

    Use arrow function instead of function, comma operator instead of return, and currentIndex in reduce callback.

    [5, 10, 3, 2].reduce((r, a, i) => (r.push((i && r[i - 1] || 0) + a), r), []); // [ 5, 15, 18, 20 ]
    
    0 讨论(0)
  • 2020-11-27 07:02
    var nums= [5, 10, 3, 2];
    var runningSum = function(nums) {
       
        nums.reduce((acc, _, i) => (nums[i] += acc));
        return nums;
    };
    
    0 讨论(0)
  • 2020-11-27 07:03
    /**
     * Turn an array of numbers to cumulative sum array
     * @param { Array } [1,2,3,4,5]
     * @return { Array } [1,3,6,10,15]
     */
    
    const accumulate = (a, c) => a + c
    
    const cusum = arr => arr.map((v, i, data) => {
        return data.slice(0, i + 1).reduce(accumulate)
    })
    
    0 讨论(0)
  • 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]))
    
    0 讨论(0)
  • 2020-11-27 07:04

    Old school and simpler :

    let myarray = [5, 10, 3, 2], result = [];
    
    for (let i = 0, s = myarray[0]; i < myarray.length; i++, s += myarray[i]) result.push(s);
    
    console.log(result); // [5, 15, 18, 20]
    
    0 讨论(0)
  • 2020-11-27 07:05

    Another clean one line solution with reduce and concat

    var result = myarray.reduce(function(a,b,i){ return i === 0 ?  [b]: a.concat(a[i-1]+b);},0);
    //[5, 10, 3, 2] => [5, 15, 18, 20]
    
    0 讨论(0)
提交回复
热议问题