I have the following array and I need to calculate the sum of the values per group. I can get the sum for each group for the first value at dataArr[1] of the array, but I need to also get the sum for the second value at dataArr[2] for each group in the array.
var dataArr = [ [
"Group One",
1,
1
],
[
"Group Four",
0,
1
],
[
"Group Three",
0,
1
],
[
"Group Three",
1,
0
],
[
"Group Four",
0,
1
],
[
"Group Two",
2,
1
],
[
"Group Four",
1,
0
],
[
"Group Three",
0,
1
],
[
"Group Three",
0,
1
],
[
"Group One",
1,
0
],
[
"Group Three",
0,
1
],
[
"Group Two",
1,
0
]
];
How to calculate the sum of the second value and generate a multidimensional array like the following:
[["Group One", 2, 1], ["Group Four", 1, 2], ["Group Three", 1, 4], ["Group Two", 3, 1]]
Below is my code inspired from here:
var result = [];
$(dataArr).each(function() {
var key = this[0];
var value = this[1];
if (result[key]) {
result[key] += value;
} else {
result[key] = value;
}
});
This proposal uses a temporary object for the reference to the result array.
var dataArr = [["Group One", 1, 1], ["Group Four", 0, 1], ["Group Three", 0, 1], ["Group Three", 1, 0], ["Group Four", 0, 1], ["Group Two", 2, 1], ["Group Four", 1, 0], ["Group Three", 0, 1], ["Group Three", 0, 1], ["Group One", 1, 0], ["Group Three", 0, 1], ["Group Two", 1, 0]],
result = function (data) {
var r = [], o = {};
data.forEach(function (a) {
if (!o[a[0]]) {
o[a[0]] = [a[0], 0, 0];
r.push(o[a[0]]);
}
o[a[0]][1] += a[1];
o[a[0]][2] += a[2];
});
return r;
}(dataArr);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With