For a smallish array, you can do it by repeating looking for other matching rooms:
const newRooms = rooms.filter((room, index) => {
// Only include this room if there isn't another room earlier
// in the array that has the same values
return !rooms.some((r, i) =>
i < index &&
r.room_rate_type_id == room.room_rate_type_id &&
r.price == room.price
);
});
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) => {
// Only include this room if there isn't another room earlier
// in the array that has the same values
return !rooms.some((r, i) =>
i < index &&
r.room_rate_type_id == room.room_rate_type_id &&
r.price == room.price
);
});
console.log(newRooms);
.as-console-wrapper {
max-height: 100% !important;
}
If the array is really large, that gets inefficient and you may be better off remembering combinations you've seen before rather than constantly re-searching the array:
const seenRooms = Object.create(null);
const newRooms = rooms.filter((room, index) => {
const key = room.room_rate_type_id + "**" + room.price;
if (seenRooms[key]) {
return false;
}
seenRooms[key] = true;
return true;
});
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 seenRooms = Object.create(null);
const newRooms = rooms.filter((room, index) => {
const key = room.room_rate_type_id + "**" + room.price;
if (seenRooms[key]) {
return false;
}
seenRooms[key] = true;
return true;
});
console.log(newRooms);
.as-console-wrapper {
max-height: 100% !important;
}
Those are written for clarity; you can make them more concise if you like.
I am currently removing duplicates objects from the array, well technically your not, your creating a new array from a filter.. :)