Creating an array of cumulative sum in javascript

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

    use reduce to build the result directly and non-destructively.

    a.reduce(function(r,c,i){ r.push((r[i-1] || 0) + c); return r }, [] );
    
    0 讨论(0)
  • 2020-11-27 06:56

    Simple solution using for loop

    var myarray = [5, 10, 3, 2];
    
    var output = [];
    var sum = 0;
    
    for(var i in myarray){
      sum=sum+myarray[i];
      output.push(sum)
    }
    console.log(output)
    

    https://jsfiddle.net/p31p877q/1/

    0 讨论(0)
  • 2020-11-27 06:58

    Simple solution using ES6

    let myarray = [5, 10, 3, 2];
        let new_array = [];  
        myarray.reduce( (prev, curr,i) =>  new_array[i] = prev + curr , 0 )
        console.log(new_array);

    For more information Array.reduce()

    Arrow function

    0 讨论(0)
  • 2020-11-27 06:59

    I needed to keep the results and just add a running total property. I had a json object with a date and revenue and wanted to display a running total as well.

    //i'm calculating a running total of revenue, here's some sample data
    let a = [
      {"date":  "\/Date(1604552400000)\/","revenue":  100000 },
      {"date":  "\/Date(1604203200000)\/","revenue":  200000 },
      {"date":  "\/Date(1604466000000)\/","revenue":  125000 },
      {"date":  "\/Date(1604293200000)\/","revenue":  400000 },
      {"date":  "\/Date(1604379600000)\/","revenue":  150000 }
    ];
    
    //outside accumulator to hold the running total
    let c = 0;
    
    //new obj to hold results with running total
    let b = a
      .map( x => ({...x,"rtotal":c+=x.revenue}) )
      
    //show results, use console.table if in a browser console
    console.log(b)

    0 讨论(0)
  • 2020-11-27 07:00

    A simple function using array-reduce.

    const arr = [6, 3, -2, 4, -1, 0, -5];
    
    const prefixSum = (arr) => {
    
      let result = [arr[0]]; // The first digit in the array don't change
      arr.reduce((accumulator, current) => {
           result.push(accumulator + current);
    
           return accumulator + current; // update accumulator
      });
      return result;
    }
    
    0 讨论(0)
  • 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 })
    
    0 讨论(0)
提交回复
热议问题