Sum values from an Array in JavaScript

前端 未结 10 1081
离开以前
离开以前 2020-12-02 18:17

I have defined a JavaScript variables called myData which is a new Array like this:

var myData = new Array([\'2013-01-22\', 0], [\'         


        
相关标签:
10条回答
  • 2020-12-02 18:35

    Or in ES6

    values.reduce((a, b) => a + b),

    example:

    [1,2,3].reduce((a, b)=>a+b) // return 6
    
    0 讨论(0)
  • 2020-12-02 18:39

    Old way (if you don't now the length of arguments/parameters)

     >> function sumla1(){
    
        result=0
        for(let i=0; i<arguments.length;i++){
    
            result+=arguments[i];
    
        }
        return result;
        }
        >> sumla1(45,67,88);
        >> 200
    

    ES6 (destructuring of array)

    >> function sumla2(...x){return x.reduce((a,b)=>a+b)}
    >>
    >> sumla2(5,5,6,7,8)
    >>
    >> 31
    >>
    >> var numbers = [4, 9, 16, 25];
    >> sumla2(...numbers);
    >> 54
    
    0 讨论(0)
  • 2020-12-02 18:41

    If you want to discard the array at the same time as summing, you could do (say, stack is the array):

    var stack = [1,2,3],
        sum = 0;
    while(stack.length > 0) { sum += stack.pop() };
    
    0 讨论(0)
  • 2020-12-02 18:42

    You could use the Array.reduce method:

    const myData = [
      ['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
      ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
      ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
      ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]
    ];
    const sum = myData
      .map( v => v[1] )                                
      .reduce( (sum, current) => sum + current, 0 );
      
    console.log(sum);

    See MDN

    0 讨论(0)
  • 2020-12-02 18:42

    I think the simplest way might be:

    values.reduce(function(a, b){return a+b;})
    
    0 讨论(0)
  • 2020-12-02 18:44

    The javascript built-in reduce for Arrays is not a standard, but you can use underscore.js:

    var data = _.range(10);
    var sum = _(data).reduce(function(memo, i) {return memo + i});
    

    which becomes

    var sumMyData = _(myData).reduce(function(memo, i) {return memo + i[1]}, 0);
    

    for your case. Have a look at this fiddle also.

    0 讨论(0)
提交回复
热议问题