Checking for duplicates in a TypeScript array of objects

I am facing a requirement where I must check for duplicates among object items.

Within the following Array of objects, I need to specifically look for duplicates in either the "empno" or "extension" properties. If any duplicates are found, an error should be triggered.

I attempted using this Stack Overflow link as a reference, but unfortunately, it did not provide the solution I needed.

[
    {
        "id": 269,
        "empno": "34567",
        "extension": 345
    },
    {
        "id": 269,
        "empno": "34568",
        "extension": 346
    },
    {
        "id": 269,
        "empno": "34569",
        "extension": 345
    },
    {
        "id": 269,
        "empno": "34567",
        "extension": 345
    }
]

Answer №1

To efficiently check for duplicates in a dataset, one approach is to use a Set to store unique combinations of values:

const hasDuplicates = (data) => {
  const set = new Set();

  for (let {empno, extension} of data) {
    const key = `${empno}/${extension}`;
    if (set.has(key)) {
      return true;
    }

    set.add(key);
  }

  return false;
};

Complete code snippet:

const data = [{
    "id": 269,
    "empno": "34567",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34568",
    "extension": 346
  },
  {
    "id": 269,
    "empno": "34569",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34567",
    "extension": 345
  }
];

const hasDuplicates = (data) => {
  const set = new Set();
  
  for (let {empno, extension} of data) {
    const key = `${empno}/${extension}`;
    if (set.has(key)) {
      return true;
    }
    
    set.add(key);
  }
  
  return false;
};

console.log(hasDuplicates(data));


For a more concise solution that checks for duplicates by comparing the size of the array with a Set, you can use the following code snippet:

const hasDuplicates = (data) => data.length !== data.reduce((a, {empno, extension}) => a.add(`${empno}/${extension}`), new Set).size;

Complete code snippet:

const data = [{
    "id": 269,
    "empno": "34567",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34568",
    "extension": 346
  },
  {
    "id": 269,
    "empno": "34569",
    "extension": 345
  },
  {
    "id": 269,
    "empno": "34567",
    "extension": 345
  }
];

const hasDuplicates = (data) => data.length !== data.reduce((a, {empno, extension}) => a.add(`${empno}/${extension}`), new Set).size;

console.log(hasDuplicates(data));

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

Trouble arises from the object data type not being properly acknowledged in TypeScript

In the code snippet provided, I am facing a challenge where I need to pass data to an if block with two different types. These types are handled separately in the if block. How can I make TypeScript understand that the selected object could be either of ty ...

Is it possible to generate two output JSON Objects for a JavaScript line chart?

How can I display two lines in a Chart.js line chart using data from a JSON file with 2 objects stored in the database? When attempting to show both sets of data simultaneously, I encountered an issue where the output was always undefined. Why is this hap ...

Setting a property with a generic type array: Tips and tricks

Currently, I am working on implementing a select component that can accept an array of any type. However, I am facing some challenges in defining the generic and where to specify it. My project involves using <script setup> with TypeScript. Here is ...

Implement Angular backend API on Azure Cloud Platform

I successfully created a backend API that connects to SQL and is hosted on my Azure account. However, I am unsure of the steps needed to deploy this API on Azure and make it accessible so that I can connect my Angular app to its URL instead of using loca ...

Unraveling the RxJs enigma: Sharing a stream and selectively retrying it upon fresh subscription

Scenario: Our web application has the capability to show multiple help panels simultaneously. When a panel requires a specific ID (ex: help-id-1), we make a call to an API with that ID and retrieve the necessary help content. Sometimes, we may need to ...

Eliminate the need for index.html in the URL when using MVC WebApi

I am currently utilizing Angular for the front end and have an index.html page as the starting point. On the main page, the URL appears as follows: localhost:588/index.html#/ I desire it to appear as: localhost:3478/#/ or simply localhost:3478/ The iss ...

Exploring Problems with Cookies in Angular

I am attempting to store data in cookies using Angular, but for some reason it doesn't seem to be working. Here is the function I created to store the cookie: Store the cookie $scope.saveToCookie = function(name, id){ var bestCityName = nam ...

The console indicates that the state's arrays have been filled, yet I'm unable to retrieve the object[0]

In my code, the functions that populate the state are called on component will mount. When I log the state on the render, this is what I observe in the log. The log clearly shows that the arrays in the state have been populated, although there seems to be ...

HTML Toggle Menu Vanishing Act

I've designed a sleek HTML menu with media queries, and integrated a Menu Hook that uses jquery's slideToggle for smaller devices. Everything works perfectly when toggling the menu to show and then maximizing the screen. However, if I hide the me ...

Handling Camera Positioning and Direction in Three.js: Utilizing Orbit Controls and camera

Having trouble getting Orbit Controls to function correctly after setting the camera to : camera.up.set(0,0,1) This results in improper orbiting behavior, and there are some unresolved questions online addressing this issue: Three.js: way to change the u ...

Is there an equivalent of HtmlSpecialChars in JavaScript?

It seems that finding this is proving more difficult than anticipated, even though it's such a simple concept... Is there an equivalent function in JavaScript to PHP's htmlspecialchars? While it's possible to create your own implementation, ...

Unlimited possibilities with parameters on an express server

I've set up React Router with recursive parameters, similar to the example here. On my Express server, I'm attempting to handle routes like /someRoute/:recursiveParameter? router.get('/someRoute/:recursiveParameter?', async (req, res ...

You can eliminate the display flex property from the MuiCollapse-wrapper

Having trouble removing the display flex property from the MuiCollapse-wrapper, I did some research and found the rule name for the wrapper in this link https://material-ui.com/api/collapse/ I have been unsuccessful in overwriting the class name wrapper t ...

When I try to install dependencies with Hardhat, the "Typechain" folder does not appear in the directory

After installing all the dependencies, I noticed that the "typechain" folder was missing in the typescript hardhat. How can I retrieve it? Try running npm init Then, do npm install --save-dev hardhat Next, run npx hardaht You should see an option to se ...

What is the best way to retrieve the request object within a Mongoose pre hook?

Is there a way to have the merchantID in documents automatically set to the logged-in user found in req.user when saving them? product.model.js: const ProductSchema = new Schema({ merchantId: { type: ObjectId, ref: "Merchant", requ ...

After retrieving parameters from the URL, the prior URL remains when I use res.render to load the page

When the task is to retrieve a product based on its product_id, for example hitting localhost:8080/products/44566 should respond with the product page for the specific product with the id 44566. In the Home page where products are displayed and clicking o ...

Using AngularJS to create a placeholder for a <select> element within ng-repeat

I’ve been facing a challenge while trying to insert a placeholder within an html select tag utilizing ng-repeat for an AngularJS application. Here is the JS fiddle link This is how my HTML structure appears: <div ng-repeat="item in items"> <d ...

Why is it that the game board component is not appearing on my HTML page?

I am currently facing an issue with a loop in my Angular html file: <div class="board" #board> <div class="row" *ngFor="let row of this.board; let i = index"> <div *ngFor=" ...

Unable to animate a second click using jQuery/CSS

I'm having an issue with animating on click using CSS. The animation works fine on the first click, but it doesn't work on the second click. This is because the click event is being overridden by jQuery to enable the dropdown menu to open onClick ...

Adding an overlay to a material UI table row: Step by step guide

My code is rendering a row in the following format: `<TableRow key={row.name} > <TableCell>{row.empId}</TableCell> <TableCell>{row.userId}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{r ...