Question

I had a double array in Jquery like this :

total_value_year = {
{'2014', 1500},
{'2015', 1000},
{'2014', 150},
{'2015', 200},
{'2015', 50},
...
}

There is always only two years possible, i want to add up all the value for the same years. At the end i want to have theses datas :

2014 => 1650, 2015 => 1250

Was it helpful?

Solution

Try this http://jsbin.com/sahasira/1/edit

total_value_year = [
 ['2014', 1500],
 ['2015', 1000],
 ['2014', 150],
 ['2015', 200],
 ['2015', 50]
];
var arr = {};
total_value_year.forEach(
  function (item, index) {
    arr[item[0]] = (arr[item[0]] || 0) + item[1];
  }
);
console.log(arr["2014"]);
console.log(arr["2015"]);

OTHER TIPS

Not very sure if it is the string in the mentioned format is what you need but I have tried out the following. Please check if it suites you.

var total_value_year = [
    ['2014', 1500],
    ['2015', 1000],
    ['2014', 150],
    ['2015', 200],
    ['2015', 50]
    ]

var year1 = '', year2 = '', sumyear1 = 0, sumyear2 = 0;

$.each(total_value_year, function (key, value) {
    if (key == 0) {
        year1 = value[0];
        sumyear1 = value[1];
    }
    else {
        if (year1 == value[0]) {
            sumyear1 = sumyear1 + value[1];
        }
        else {
            year2 = value[0];
            sumyear2 = sumyear2 + value[1];
        }
    }
});
alert(year1 + ' => ' + sumyear1 + ', ' + year2 + ' => ' + sumyear2);

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top