Determine whether or not there are any duplicate elements within an array object

Is there a way to determine true or false if there are any duplicates within an object array?

arr = [
     { nr:10, name: 'aba' },
     { nr:11, name: 'cba' },
     { nr:10, name: 'aba' }
]

 arr2 = [
         { year:2020, city: 'Aaa' },
         { year:2010, city: 'Bbb' },
         { year:2020, city: 'Aaa' }
    ]

While there are numerous solutions available for checking duplicate values, what if we need to check the entire object? Would using a foreach loop be necessary?

 const result: T[] = [];
    for (const item of array) {
        if (!result.includes(item)) {
            result.push(item);
        }
    }
    return result;

Answer №1

To check for duplicates in an array, you can utilize JSON.stringify along with the map and some array methods.

let arr = [
     { nr:10, name: 'aba' },
     { nr:11, name: 'cba' },
     { nr:10, name: 'aba' }

]


 let valuesStringify = arr2.map(x => JSON.stringify(x));

 let duplicate = valuesStringify.some((item, i) => valuesStringify.indexOf(item) !== i)

console.log(duplicate) //true

Click here for the example

Answer №2

Utilizing a combination of Array.prototype.some, Array.prototype.every, and Object.entries

This method iterates through each item in the array compared to the remaining items in the array (slice(index + 1)) to determine if any objects are identical.

function hasDuplicates(arr) {
  // compare each item in the array with the rest of the array
  return arr.some((obj, index) => arr.slice(index + 1).some(obj2 => {
    // check if obj is equal to obj2
    return Object.entries(obj).every(([key, value]) => obj2[key] === value)
  }))
}

let arr = [
  { nr:10, name: 'aba' },
  { nr:11, name: 'cba' },
  { nr:10, name: 'aba' }
];

let arr2 = [
  { year:2020, city: 'Aaa' },
  { year:2010, city: 'Bbb' },
  { year:2020, city: 'Ccc' }
];

console.log(hasDuplicates(arr)); // true
console.log(hasDuplicates(arr2)); // false

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

Solving the issue of loading Ember Initializers during the transition to TypeScript

While following the ember quick start tutorial, I attempted to switch from Javascript to Typescript. Converting the .js files to .ts files resulted in an error with the ember-load-initializers import. The application is unable to run until this issue is re ...

Cease the animated loading icon once the template has finished loading in sync with the async pipe

.ts initialize() { const loadingScreen = await this.loadingService.displayLoader();//loading screen this.products$ = this.bikeShopService.retrieveData();//Observable operation } .html <ion-col size="6" *ngFor="let product of (products$ ...

Filtering a multi-dimensional array in Ionic 3

I attempted to filter an array from a JSON with the following structure {ID: "2031", title: "title 1", image: "http://wwwsite.com/im.jpg", url: "url...", Goal: "3000000", …} The array is named 'loadedprojects' and below is the filteri ...

Enhance Your NestJS Experience: Using Interceptors for Mapping and Error Handling

I'm looking for a NestJS interceptor that can log requests in all scenarios, including both successful executions and errors. Below is an example implementation: public intercept(context: ExecutionContext, next: CallHandler): Observable<any> { ...

Peer dependencies in NPM refer to dependencies that your project

I am currently in the process of upgrading from Angular 4 to Angular 5 and encountered some warnings along the way. Some of the warnings I received include: npm WARN @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88eb ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

Nuxt 3 turns a blind eye to TypeScript errors upon code saving

I am facing an issue. Even with a TypeScript error in the code, the IDE shows an error, but I am still able to save it and run it in the browser. Is this acceptable? Check out the code below: <script lang="ts" setup> const a = ref<strin ...

Utilizing Angular's microservice architecture to dynamically load modules from a provided

Recently, I've been contemplating the best way to integrate Angular into a microservices architecture. Imagine we have separate services for login, user management, and media browsing, adding, and editing - each with its own backend and frontend in i ...

Perform an additional HTTP request and utilize the response within the existing Observable

In my Angular 2 project, I am utilizing the http component to make API calls. The specific REST API I want to access returns a maximum of 100 Elements in one request. If more items exist, a hasMore flag is included in the response. To retrieve additional ...

Typescript React: Implementing type definitions for JSS classes object

Here is the react code I am working with: import React from 'react'; import withStyles from "react-jss"; const styles = { box: { border: "2px solid #000" } }; interface ComponentProps {} class Welcom ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...

The most efficient method for personalizing the production baseUrl is using the angular2-webpack-starter

Currently, I am utilizing angular2-webpack-starter version 5.4.1. If you want to find out more about it, you can visit their GitHub page here. In order to adjust the baseUrl for the production build, I found myself repeating the same steps that were outli ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : https://i.sstatic.net/myJAf.png On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Ri ...

Perplexed by the implementation of "require(...)" in TypeScript

After reading several blog posts, my understanding of TypeScript modules remains confusing. I have worked with three different modules (all installed via npm) and encountered varying behavior: (1) Importing and using Angular 2 from npm required me to add ...

What is the best way to utilize project references with multiple tsconfig files?

Let's say I have three separate projects to work on: shared frontend backend In order to use the shared project as a reference in both the frontend and the backend, I need to make a few adjustments. The backend utilizes commonjs modules while the fr ...

I am encountering difficulties while attempting to import Typescript files. Upon compiling them into Javascript, I am faced with errors in the web browser, specifically the issue of "exports is not defined"

When I run TodoAppUI.js:15, I get an error saying "Uncaught ReferenceError: exports is not defined" In all my classes, I use the export keyword. For example: export class mysclass { public constructor(){} } Even though I have the proper syntax for impo ...

Best practices for transferring date objects between a frontend developed in JavaScript/TypeScript and a backend built in ASP.net Core 5

An exciting project I am working on involves a web application with a backend REST web API developed in ASP.net Core 5 and a frontend Angular application written in TypeScript. One of the APIs from the ASP.net backend returns an instance of a C# object de ...