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);
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.
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.
You can do
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
You can reduce the array to a Map object by creating a key from both properties, and adding the object to the Map only if the key doesn't already exist. Then spread the Map#values back to an array:
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.reduce((m, r) => {
const key = `${r.room_rate_type_id}-${r.price}`; // create the key by combining both props
return m.has(key) ? m : m.set(key, r); // if key exists skip, if not add to map
}, new Map()).values()]; // get the map values and convert back to array
console.log(newRooms);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With