Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates objects in array based on 2 properties?

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.

like image 395
Stephan-v Avatar asked Aug 26 '26 00:08

Stephan-v


2 Answers

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

like image 83
marvel308 Avatar answered Aug 27 '26 15:08

marvel308


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);
like image 38
Ori Drori Avatar answered Aug 27 '26 15:08

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!