[英]filtering an array: get max price and unique objects?
store = [{ "item": "shirt", "price": 20 }, { "item": "shirt", "price": 50 }, { "item": "pants", "price": 10 }, { "item": "pants", "price": 20 } ] //im filtering the array to get objects without duplication here console.log(store.filter((v, i, a) => a.findIndex(v2 => ['item'].every(k => v2[k] === v[k])) === i))
我也想在同一个过滤器中获得最高价格,所以我如何在执行后获得这个 output?
预计 output:
[{
"item": "shirt",
"price": 50
},
{
"item": "pants",
"price": 20
}]
您可以在过滤之前按价格对它们进行sort()
。
store = [{ "item": "shirt", "price": 20 }, { "item": "shirt", "price": 50 }, { "item": "pants", "price": 10 }, { "item": "pants", "price": 20 } ] const result = store.sort((a, b) => b.price - a.price).filter((v, i, a) => a.findIndex(v2 => ['item'].every(k => v2[k] === v[k])) === i); console.log(result);
我喜欢@axtck 的回答。 ....过滤对象后,现在使用.map()
通过排序从原始数据中找到最高价格:
.map(
({item,price}) =>
({item,price:store.filter(p => p.item === item).sort((a,b) => b.price - a.price)[0].price})
)
store = [{ "item": "shirt", "price": 20 }, { "item": "shirt", "price": 50 }, { "item": "pants", "price": 10 }, { "item": "pants", "price": 20 } ] //im filtering the array to get objects without duplication here console.log( store.filter((v, i, a) => a.findIndex(v2 => ['item'].every(k => v2[k] === v[k])) === i).map( ({item,price}) => ({item,price:store.filter(p => p.item === item).sort((a,b) => b.price - a.price)[0].price}) ) )
您可以使用Array.reduce()
来获取每件商品的最高价格。
我们将枚举每个值,创建 map object,如果该项目不存在条目或现有条目的价格较低,我们将更新:
const store = [{ "item": "shirt", "price": 20 }, { "item": "shirt", "price": 50 }, { "item": "pants", "price": 10 }, { "item": "pants", "price": 20 } ] const result = Object.values(store.reduce((acc, { item, price }) => { // Either item does not exist or has a lower price... if (.acc[item] || acc[item],price < price) { acc[item] = { item; price }; } return acc, }. {})) console.log(result)
.as-console-wrapper { max-height: 100%;important; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.