What is the best method for eliminating duplicate objects in an array using 2 specific properties?

I am currently dealing with an array of room objects and my task involves removing duplicate objects 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);

In addition to eliminating duplicates based on the room_rate_type_id, I now have a requirement to include price comparison as well when removing objects.

While I grasp the concept of using the filter method in this scenario, I am seeking guidance on how to efficiently incorporate a price check along with room_rate_type_id match, preferably utilizing ES6 syntax.

Answer №1

To accomplish this task, you can use the following JavaScript code:

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 code snippet will filter out all duplicates except for the first occurrence of any object in the array.

Answer №2

To transform the array into a Map object, you can generate a unique key using properties from each element and then add the element to the Map only if the key is not already present. Finally, convert the values of the Map back into an array using the spread operator:

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 a unique key by combining both properties
  return m.has(key) ? m : m.set(key, r); // skip if key exists, else add to map
}, new Map()).values()]; // retrieve map values and convert them back to an array

console.log(newRooms);

Answer №3

To handle a small array efficiently, you can filter out matching rooms by checking for duplicates:

const newRooms = rooms.filter((room, index) => {
  // Include room only if no previous room matches it
  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 dealing with a large array, it's more efficient to store seen combinations and avoid rechecking every time:

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;
}

The examples are written for clarity; feel free to simplify them further as needed.

Answer №4

An easy method: creating a unique key by combining the room_rate_type_id and price values:

const rooms = [
    {room_rate_type_id: 303, price: 150},{room_rate_type_id: 305, price: 200}, {room_rate_type_id: 303, price: 150}
];

const roomKeys = [];
const filteredRooms = rooms.filter((room, index, arr) => {
    let key = room.room_rate_type_id + "" + room.price;
    if (roomKeys.indexOf(key) === -1) {
        roomKeys.push(key);
        return room;
    }
});

console.log(filteredRooms);

Answer №5

If you're looking for a solution, the following code snippet should help:

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((uniqueRooms, room) => {
  let foundRoom = uniqueRooms.filter(r => {
    return r.room_rate_type_id === room.room_rate_type_id && r.price === room.price;
  });
  if (foundRoom.length === 0) {
    return [...uniqueRooms, room];
  }
  return uniqueRooms;
}, [rooms[0]]);

console.log(newRooms);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №6

const roomList = [
  {
    id: 101,
    rate: 150
  },
  {
    id: 101,
    rate: 150
  },
  {
    id: 101,
    rate: 175
  },
  {
    id: 111,
    rate: 200
  }
];

let filteredRooms = roomList.filter((room, index, array) => array.findIndex(x => x.id === room.id && x.rate === room.rate) === index);


console.log(filteredRooms);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error callback in Jquery ajax is triggered despite receiving a 200 status code in the response

I am facing an issue with my ajax code. The success callback contains an alert that is not working properly. Here is the code snippet: $(".change_forex_transaction_status").click(function(){ $("#insufficient_funds").css("display","none"); var id = $( ...

Determining the Width of an Image Following the Application of a CSS Class Using Javascript

I have a custom script that is able to determine whether an image is in portrait or landscape orientation. Currently, the image is identified as being in landscape mode. My goal here is to crop and center the image using absolute positioning, specifying a ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

What is the secret to remaining on the same spot even after the page is reloaded?

How can I maintain the AJAX call data after a page reload? I have attempted to use code that reloads the entire page, but I would like to stay in the same location. Is there a way to achieve this without reloading the entire page? $('#updateAddressPr ...

Connect the value of the input field to the dataset

In my current project, I am implementing ng-repeat to showcase a collection of items. Each item includes a line number, an HTML input field for quantity input, and an itemId. I am currently exploring ways to connect the input value with the quantity field ...

Uploading files with Ajax in PHP

Illustration of my Ajax script: Script <script type="text/javascript> $(document).ready(function(){ $('.costExcel').on("submit",function(event){ event.preventDefault() var url = "ajax.php"; ...

Conceal information on-the-fly using React

I am seeking a way to dynamically hide irrelevant items based on their tags. This functionality should only be applied to tags with a "taglevel" higher than 1. For instance, if I select the tag "books," only the tags "adventure" and "classic" should be d ...

Having trouble launching an Angular 2 project

Something strange just happened to my Angular 2 project. Suddenly, I can't seem to start it anymore, and I'm stuck trying to figure out why based on the error messages... node_modules/@types/core-js/index.d.ts(21,14): error TS2300: Duplicate ide ...

collection of elements and lineage

In this scenario, I have a base class Class A, with derived classes Class B and Class C extending from A. Additionally, there is a class D that contains a data member (pointer to an array) of type A using composition. enter code here class D{ A **a; int ...

Java Script Event Handling Creating Array with Numerous Duplicates

While attempting to recreate the Simon game, I am working on adding click events to an array and testing that Array in a nested function immediately. Initially, everything seems to be functioning correctly. However, after the third run, the array does not ...

Harnessing the power of jQuery.load() and ajax dataFilter() for dynamic content loading

Recently, I encountered a situation where I was utilizing jQuery.load() to bring in the content of an HTML page into a lightbox. The beauty of the load function lies in its ability to transform complete HTML pages into neat HTML fragments that can easily b ...

Can you provide me with the sequelize query that is equivalent to this raw query?

Retrieve the ID from the offers table where the user ID is not equal to '2' and the ID is not present in the list of notified offers for user '2'. ...

What leads to the occurrence of the "maximum call stack size exceeded" error?

I am currently developing a Vue 3 and Bootstrap 5 application. To integrate a date-picker functionality, I opted for the Vue 3 Datepicker plugin available at Vue 3 Datepicker. Within the file components\Ui\Datepicker.vue, I have included the fol ...

Guidelines for setting the Id and value for a Hidden field

I am working with a gridview that has a few rows and columns, each containing ListBox Controls. Markup: <asp:GridView ID="gvDataEntry" runat="server" AutoGenerateColumns="False" <Columns> <ItemTemplate> <asp:ListBox ID="lst ...

What is causing the TouchSwipe jQuery plugin not to function in my code?

I have integrated the TouchSwipe jQuery plugin into my code to detect mouse movement and display the number of pixels moved when swiping left or right. To download the TouchSwipe jQuery plugin, I visited this link: TouchSwipe and then proceeded to use it ...

Manage the orientation of the text for entering dates

I need to customize a textfield to enter dates in the format of yyyy/MM/dd. The input direction is set to rtl. However, when I enter the day, then month, and then year, the final displayed values show up as dd/MM/yyyy, as shown in the image attached: My g ...

What are the best methods for saving long-term offline data in Progressive Web Apps using browser storage?

Can permanent data be stored in offline storage within a web browser? I have been struggling to find a solution and would appreciate any help you can provide. I've gone through some tutorials but haven't found them to be useful. Thank you in ad ...

"Exploring the concept of undefined within object-oriented programming and its role in

Recently diving into Express and trying out routing by creating an object in a file to export. import userController from "../controllers/userController.js" // get all users router.get("/", isAuth, isAdmin, userController.list) Encoun ...

The search text box is mysteriously absent from each column in the datatables

I am utilizing jQuery Datatables to construct a table with data retrieved from MySQL. This is how my table appears: LOT_LOCATION, Zone Attribute, LOTID, Design_ID, Board_ID1, QA_WORK_REQUEST_NO, QA_CONTACT_NAME, QA_PROCESS_NAME, CURRENT_QTY, Date, Temp ...