संपादित करें: इसे अभी तक छोड़ना, लेकिन मैं पूरी तरह से _.flatten के बारे में भूल गया, इसलिए redmallard को much better answer मिला।
आप पहले से ही उत्पादों के नाम से जानते हैं और वे हर समूह में दिखाई हैं, तो आप पूरी बात जल्दी से इस तरह से कर सकता है:
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']);
मैं एक साथ डाल, जो काम करना चाहिए, भले ही आपके समूहों विभिन्न उत्पादों है (उदाहरण के लिए "एक" प्रथम, द्वितीय, और चौथे समूह में और "दो" पहले और तीसरे में):
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
};
});
तुम अब भी कर सकता है एक काउंटर के साथ एक समारोह में और कीमतों संक्षेप ऊपर है, लेकिन इस तरह से , यदि आप चाहते हैं कि कीमतें भी हों, तो मानक डी लें विचलन या मोड ढूंढें।
कहाँ '400' से आता है? – georg