如何根据2个属性删除数组中的重复对象? [英] How to remove duplicates objects in array based on 2 properties?
问题描述
我有一组房间对象,我正在根据他们的 room_rate_type_id
属性从数组中删除重复对象:
I have an array of room objects and I am currently removing duplicates objects from the array based on their room_rate_type_id
property:
const rooms = [{
room_rate_type_id: 202,
price: 200
},
{
room_rate_type_id: 202,
price: 200
},
{
room_rate_type_id: 202,
price: 189
},
{
room_rate_type_id: 190,
price: 200
}
];
const newRooms = rooms.filter((room, index, array) => {
const roomRateTypeIds = rooms.map(room => room.room_rate_type_id);
// Returns the first index found.
return roomRateTypeIds.indexOf(room.room_rate_type_id) === index;
});
console.log(newRooms);
但是我还需要确保只有<* c $ c> room_rate_type_id $ c $才能删除对象c>匹配,但他们的pric即
However I also need to make sure that objects only get removed if not only their room_rate_type_id
matches but also their price.
我可以理解过滤器功能在我给出的示例中是如何工作的,但我不确定如何干净地检查价格,最好是在ES6中。
I can understand how the filter functionality works in my given example but I am unsure how to cleanly do a check for the price as well, preferably in ES6.
推荐答案
你可以做到
const rooms = [
{
room_rate_type_id: 202,
price: 200
},
{
room_rate_type_id: 202,
price: 200
},
{
room_rate_type_id: 202,
price: 189
},
{
room_rate_type_id: 190,
price: 200
}
];
let result = rooms.filter((e, i) => {
return rooms.findIndex((x) => {
return x.room_rate_type_id == e.room_rate_type_id && x.price == e.price;}) == i;
});
console.log(result);
这将过滤除第一次出现任何对象之外的所有重复
This would filter all duplicates except the first occurrence of any object
这篇关于如何根据2个属性删除数组中的重复对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!