Sum values from an Array in JavaScript

前端 未结 10 1082
离开以前
离开以前 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:48

    I would use reduce

    var myData = new Array(['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]);
    
    var sum = myData.reduce(function(a, b) {
        return a + b[1];
    }, 0);
    
    $("#result").text(sum);
    

    Available on jsfiddle

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

    You can use the native map method for Arrays. map Method (Array) (JavaScript)

    var myData = new Array(['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]);
    var a = 0;
    myData.map( function(aa){ a += aa[1];  return a; });
    

    a is your result

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

    Creating a sum method would work nicely, e.g. you could add the sum function to Array

    Array.prototype.sum = function(selector) {
        if (typeof selector !== 'function') {
            selector = function(item) {
                return item;
            }
        }
        var sum = 0;
        for (var i = 0; i < this.length; i++) {
            sum += parseFloat(selector(this[i]));
        }
        return sum;
    };
    

    then you could do

    > [1,2,3].sum()
    6
    

    and in your case

    > myData.sum(function(item) { return item[1]; });
    23
    

    Edit: Extending the builtins can be frowned upon because if everyone did it we would get things unexpectedly overriding each other (namespace collisions). you could add the sum function to some module and accept an array as an argument if you like. that could mean changing the signature to myModule.sum = function(arr, selector) { then this would become arr

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

    Try the following

    var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];
    
    var myTotal = 0;  // Variable to hold your total
    
    for(var i = 0, len = myData.length; i < len; i++) {
        myTotal += myData[i][1];  // Iterate over your first array and then grab the second element add the values up
    }
    
    document.write(myTotal); // 22 in this instance

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