jquery array group by
Here's a plain javascript way to do it that collects the unique indexes in a map and totals them as it does, then regenerates the array with the totals:
abcArr = [["A", 10], ["B", 20], ["A",30],["C",40]];
var items = {}, base, key;
for (var i = 0; i < abcArr.length; i++) {
base = abcArr[i];
key = base[0];
// if not already present in the map, add a zeroed item in the map
if (!items[key]) {
items[key] = 0;
}
// add new item to the map entry
items[key] += base[1];
}
// Now, generate new array
var outputArr = [], temp;
for (key in items) {
// create array entry for the map value
temp = [key, items[key]]
// put array entry into the output array
outputArr.push(temp);
}
// outputArr contains the result
Working demo: http://jsfiddle.net/jfriend00/vPMwu/
Here's a way using jQuery's .each
:
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]);
});
// outputArr contains the result
document.body.innerHTML = JSON.stringify(outputArr);
Working demo: http://jsfiddle.net/jfriend00/Q8LLT/
Underscore.js has groupBy
, and the rest can be done by map
ping over reduce
(that is, reducing each group to one element
abcArr = [["A", 10], ["B", 20], ["A",30],["C",40]]
var grouped = _.groupBy(abcArr, function(x){return x[0]})
var result = _.map(grouped, function(x){
return _.reduce(x, function(x,y){
return [y[0], x[1]+y[1]];
}, [,0])
})
http://jsfiddle.net/srvKQ/
Or (minified)
abcArr = [["A", 10], ["B", 20], ["A",30],["C",40]]
var result = _.map(
_.groupBy(abcArr, function(x){return x[0]}),
function(x){return _.reduce(
x, function(x,y){return [y[0], x[1]+y[1]]}, [,0]
)});
http://jsfiddle.net/srvKQ/1/