Modifica: Lasciando perdere per ora, ma mi sono completamente dimenticato di _.flatten, quindi redmallard ha un much better answer.
Se si conosce già i nomi di prodotti e appaiono in ogni gruppo, si potrebbe fare il tutto velocemente in questo modo:
var productAveragePrices = function (groups, names) {
return _.map(names, function (name) {
var product = { name: name }, productPricesSum = 0;
_.each(groups, function (group) {
productPricesSum += (_.findWhere(group, product).price);
});
product.price = productPricesSum/_.size(groups);
return product;
});
};
var foo2 = productAveragePrices = function (foo, ['one', 'two']);
ho messo questo insieme, che dovrebbe funzionare anche se i gruppi hanno diversi prodotti (ad esempio "uno" del primo, secondo e quarto gruppo e "due" in prima e terza):
var productPriceReducer = function(memo, group) {
_.each(group, function(product) {
// Grabs the current product from the list we're compiling
var memoProduct = _.findWhere(memo, { name: product.name });
if (!memoProduct) {
// If the product doesn't exist, creates a holder for it and its prices
memoProduct = {
name: product.name,
prices: [ product.price ]
};
memo.push(memoProduct);
} else {
// Otherwise, it just adds the prices to the existing holder.
memoProduct.prices.push(product.price);
}
});
return memo;
};
// This gets us a list of products with all of their prices across groups
var productPrices = _.reduce(foo, productPriceReducer, []);
// Then reducing to the average is pretty simple!
var productAveragePrices = _.map(productPrices, function (product) {
var sumPrices = _.reduce(product.prices, function (memo, price) {
return memo + price;
}, 0);
return {
name: product.name,
price: sumPrices/product.prices.length
};
});
Si potrebbe ancora fare quanto sopra in una funzione con un contatore e sommando i prezzi, ma in questo modo , hai anche i prezzi nel caso tu voglia, per esempio, prendere lo standard d eviazione o trovare la modalità.
Dove non '400' viene? – georg