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;
}
});