我有一个数组:
var arr = [
{price: 5, amount: 100},
{price: 3, amount: 50},
{price: 10, amount: 20},
{price: 3, amount: 75},
{price: 7, amount: 15},
{price: 3, amount: 65},
{price: 2, amount: 34}
]
我想删除具有相同价格的重复项,并且只保留最后一个副本,然后根据价格从最高到最低对数组进行排序。这是我想要的结果:
var result = [
{price: 10, amount: 20},
{price : 7, amount: 15},
{price: 5, amount: 100},
{price: 3, amount: 65},
{price: 2, amount: 34}
]
答案 0 :(得分:6)
使用reduce
将对象首先转换为删除副本,最后一个副本应覆盖前一个
var obj = arr.reduce( ( acc, c ) => Object.assign(acc, {[c.price]:c.amount}) , {});
将其转换回数组并对其进行排序
var output = Object.keys( obj )
.map( s => ({ price : s, amount : obj[ s ] }) )
.sort( ( a, b ) => b.price - a.price );
<强>演示强>
var arr = [
{price: 5, amount: 100},
{price: 3, amount: 50},
{price: 10, amount: 20},
{price: 3, amount: 75},
{price: 7, amount: 15},
{price: 3, amount: 65},
{price: 2, amount: 34}
];
var obj = arr.reduce( ( acc, c ) => Object.assign(acc, {[c.price]:c.amount}) , {});
var output = Object.keys( obj )
.map( s => ({ price : s, amount : obj[ s ] }) )
.sort( ( a, b ) => b.price - a.price );
console.log( output );
答案 1 :(得分:3)
您可以使用Array.reduce
汇总数组中的结果:
var arr = [
{price: 5, amount: 100},
{price: 3, amount: 50},
{price: 10, amount: 20},
{price: 3, amount: 75},
{price: 7, amount: 15},
{price: 3, amount: 65},
{price: 2, amount: 34}
]
var results = arr.reduce<{ [price: string] : typeof arr[0] }>((p, e)=> {
p[e.price] = e
return p;
}, {});
var resultsAsArray = Object.keys(results)
.map(k=>results[k])
.sort((a, b) => b.price - a.price);
如果定义了数组项,则可以将typeof arr[0]
替换为数组项的类型。
解决方案的想法是在价格为关键的对象中累积结果,如果多次遇到相同的键,则旧值被覆盖到最后您只有最后一个值给定价格。
答案 2 :(得分:3)
我使用 reduceRight 和 splice 删除重复项。它不会创建任何无用的中间对象,只是一路上找到的独特价格列表:
var arr = [
{price: 5, amount: 100},
{price: 3, amount: 50},
{price: 10, amount: 20},
{price: 3, amount: 75},
{price: 7, amount: 15},
{price: 3, amount: 65},
{price: 2, amount: 34}
]
arr.reduceRight((acc, obj, i) => {
acc[obj.price]? arr.splice(i, 1) : acc[obj.price] = true;
return acc;
}, Object.create(null));
arr.sort((a, b) => b.price - a.price);
console.log(arr)
&#13;