简体   繁体   English

JavaScript ES6获得在同一循环迭代中映射到数组中的值的总和

[英]JavaScript ES6 get sum of values being mapped in array in the same loop iteration

I have a unique challenge that I have been trying to solve. 我一直在尝试解决一个独特的挑战。 I have an object like this: 我有一个这样的对象:

    obj = 
    [
      {item: "Skirt", price: 290}, 
      {item: "Shoes", price: 300}, 
      {item: "Skirt", price: 450}, {item: "Jeans", price: 35}
    ]

I am mapping this to get count of duplicate items with their respective average price, so that the desired output looks like: 我正在对此进行映射,以获取重复项目的计数及其各自的平均价格,以便所需的输出如下所示:

UPDATE: 更新:

obj = 
[
 {
 Skirt: 2, 
 price: 370, //2 being the count of skirt items, 370 average price
 Jeans: 1, 
 Price: 35, 
 Shoes: 1, 
 Price: 30
 }
]

I am using this function to map the items: 我正在使用此功能来映射项目:

Av_price = function(values) {
    let new_val = new Map();
       for (let x of values)
         new_val.set([x["item"]],  [(new_val.get(x["item"])|| 0) +1), (new_val.get(x["price"] || x["price"])/x["price"]])
return [...new_val.entries()];
};

The problem here is: I am able to count the number of items, say skirts, but unable to get the second value straight, I mean the prices; 这里的问题是:我能够计算物品的数量,例如裙子,但是我无法获得第二个价值,我的意思是价格; so that I can divide them by total number of items (which, in this example, are "2" for skirts, for example)! 这样我就可以将它们除以项目总数(例如,在此示例中,裙子的值为“ 2”)! This unique challenge has boggled my mind for two weeks. 这个独特的挑战使我震惊了两个星期。 Is there any way to get the count of all the skirt being mapped in the same loop iteration and then divide the sum of prices by their count to get an average price? 有什么方法可以获取在同一循环迭代中映射的所有裙的计数,然后将价格之和除以其计数即可得出平均价格?

I will be hugely thankful for the help! 我将非常感谢您的帮助!

You could take a hash table for same items and build the average out of the stored values. 您可以为相同的项目制作哈希表,然后从存储的值中构建平均值。

 var data = [{ item: "Skirt", price: 290 }, { item: "Shoes", price: 300 }, { item: "Skirt", price: 450 }, { item: "Jeans", price: 35 }], hash = Object.create(null), result = []; data.forEach(function (o) { var ref; if (!hash[o.item]) { hash[o.item] = [{ item: o.item }, [0, 0]] result.push(hash[o.item]); } ref = hash[o.item][1]; ref[1] = (ref[0] * ref[1] + o.price) / ++ref[0]; }); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

With a changed data structure for the result, you yould omit the hash table and take the result object directly. 更改结果的数据结构后,您将忽略哈希表并直接获取结果对象。

 var data = [{ item: "Skirt", price: 290 }, { item: "Shoes", price: 300 }, { item: "Skirt", price: 450 }, { item: "Jeans", price: 35 }], result = data.reduce(function (o, { item, price }) { o[item] = o[item] || 0; o[item + 'Price'] = (o[item] * (o[item + 'Price'] || 0) + price) / ++o[item]; return o; }, {}); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

let totalItems = obj.reduce((acc, {name, price}) => {
  if (!acc[name]) {
    acc[name] = 0;
    acc[`${name}Price`] = price;
  }
  acc[name] += 1;
  return acc;
}, {});

now you have the price of each item and the total number of each. 现在,您具有每个项目的价格和每个项目的总数。 The totalItems object will look something like this: totalItems对象将如下所示:

{
  skirt: 6,
  skirtPrice: 290,
  shoes: 3,
  shoesPrice: 300
}

and so on. 等等。

Use Array#reduce to create the map, which will contain the count and the summed price for each item. 使用Array#reduce创建地图,其中将包含每个项目的count和总价。 Then spread the map to entries, and Array#map it to the requested format: 然后将映射扩展到条目,并使用Array#map将其映射为请求的格式:

 const arr = [ {item: "Skirt", price: 290}, {item: "Shoes", price: 300}, {item: "Skirt", price: 450}, {item: "Jeans", price: 35} ]; const Av_price = (values) => [... new Map(values.reduce((map, { item, price }) => { const o = map.get(item) || { sum: 0, count: 0 }; o.count++; o.sum += price; return map.set(item, o); }, new Map())) ].map(([item, { count, sum }]) => [item, [count, sum/count]]); const result = Av_price(arr); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM