I have an array like this:
abcArr = [["A", "dog", 10], ["B", "cat", 20], ["A", "dog", 30],["C", "pig", 40]] ["A", "cat", 30], ["B", "cat", 20], ["A", "horse", 10];
I was looking at this post (jquery array group by) and I need something similar for my issue but I need to group my array based on 2 elements.
So my answer should look like this:
[["A", "dog", 40], ["B", "cat", 40], ["C", "pig", 40]] ["A", "cat", 30], ["A", "horse", 10];
I tried @jfriend00 's .each() approach to group just one field and it works, but I don't know how to adapt it to use two fields to group the data above.
abcArr = [["A", 10],["B", 20],["A", 30],["C", 40]];
var items = {},
base, key;
$.each(abcArr, function(index, val) {
key = val[0];
if (!items[key]) {
items[key] = 0;
}
items[key] += val[1];
});
var outputArr = [];
$.each(items, function(key, val) {
outputArr.push([key, val]);
});
console.log(outputArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Thanks.