我有一个具有以下结构的对象数组:
[ { type: 'A', rank: 10 }, { type: 'B', rank: 10 }, { type: 'A', rank: 16 }, { type: 'B', rank: 16 } ]
我想为每个 object.type 保留 1 个对象,即 object.rank 最大的对象,因此在这种情况下我的预期输出是:
[ { type: 'A', rank: 16 }, { type: 'B', rank: 16 } ]
我的代码是:
conditions = conditions.filter((cond, index, self) => self.findIndex((t) => {return t.type === cond.type && t.rank < cond.rank; }) === index);
此代码删除所有对象。当我不使用
t.rank < cond.rank
然后它可以工作,但不能保证它会返回最大的排名。
提前谢谢您,当然我不坚持使用 ES6 解决方案。
最佳答案
您可以使用 Array.reduce 的组合和 Array.findIndex以获得想要的结果。
const conditions = [{
type: 'A',
rank: 10
}, {
type: 'B',
rank: 10
}, {
type: 'A',
rank: 16
}, {
type: 'B',
rank: 16
}];
const transformed = conditions.reduce((result, item) => {
const itemIdx = result.findIndex(condition => condition.type === item.type && condition.rank < item.rank);
if (itemIdx !== -1) {
result.splice(itemIdx, 1, item);
} else {
result.push(item);
}
return result;
}, []);
console.log(transformed);
关于Node.js 过滤其中一个值重复但另一个值不重复的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220362/