As others have noted, there are no built-in JavaScript functions for this (there are several high-order functions, such as map, but not enough for the task). However, some libraries, such as Underscore.js , provide many utilities to simplify these kinds of tasks.
var totals = _
.chain(sales)
.map(function(v) {
return _
.chain(v)
.map(function(v2) {
return v2;
})
.value();
})
.flatten()
.groupBy('Region')
.map(function(g, key) {
return {
type: key,
val: _(g).reduce(function(m, x) {
return m + x.Value;
}, 0)
};
})
.value();
Source: this answer in SOpt
, - , . , Region Value - , , - , , - , , .
function aggregate(object, toGroup, toAggregate, fn, val0) {
function deepFlatten(x) {
if ( x[toGroup] !== undefined )
return x;
return _.chain(x)
.map(function(v) { return deepFlatten(v); })
.flatten()
.value();
}
return _.chain(deepFlatten(object))
.groupBy(toGroup)
.map(function(g, key) {
return {
type: key,
val: _(g).reduce(function(m, x) {
return fn(m, x[toAggregate]);
}, val0 || 0)
};
})
.value();
}
:
function add(a,b) { return a + b; }
var totals = aggregate(sales, "Region", "Value", add);
( ):
function min(a,b) { return a < b ? a : b; }
var mins = aggregate(sales, "Region", "Value", min, 999999);