Ways to verify if an array contains two identical object values?

I am in search of a way to determine whether my array contains duplicate object values or not. Let's say I have the following array of objects:

const array = [
    {
        id: "id1",
        quantity: 3,
        variation: "red",
        tax: 40
    },
    {
        id: "id1",
        quantity: 3,
        variation: "red",
        tax: 40
    },
    {
        id: "id2",
        quantity: 3,
        variation: "red",
        tax: 40
    }
]

In this case, the expected output should be true as the id1 appears twice in the array. If all IDs are unique throughout the array, then the expected output should be false. I have been struggling to find a suitable solution for this. Can someone guide me on how to achieve this?

Answer №1

Utilize this handy function:

function findDuplicates(array) {
    let hasDuplicate = false;
    let idsArray = [];

    for(let i = 0; i < array.length; i++) {
        if(idsArray.includes(array[i].id)) {
            hasDuplicate = true;
            break;
        } else {
            idsArray.push(array[i].id);
        }
    }

    return hasDuplicate;
}

console.log(findDuplicates(myArray))

Hope this solution proves helpful.

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

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

When utilizing KineticJS on a canvas that has been rotated with css3, the functionality of the events appears to be malfunctioning

Currently, I'm working on a rotating pie-chart widget using Kineticjs. However, I have run into an issue where the events don't seem to function correctly when drawing on a rotated canvas element (with the parent node being rotated 60deg using CS ...

Trigger an event when hovering over a disabled item in React using material-ui's tooltip feature

I've been trying to figure out how to hover over a disabled item with a tooltip, but it seems that disabled items don't trigger any events. I attempted wrapping my elements in another div as a workaround, but unfortunately, it didn't work. I ...

The page refreshes automatically when the search icon is clicked, but the ajax method does not trigger the page reload

Whenever I click on the search-box <a>, the JavaScript is triggered but doesn't execute the ajax method filter_data_guide_specs(). Instead, the page automatically reloads and fails to read the JS code. HTML <div class="form-group"> < ...

Guide to managing AutoComplete {onChange} in MUI version 5 with a personalized hook

Currently, I am utilizing a custom hook that manages the validation and handling of the onChange function. For most components like input, select, and textField, I have no trouble with handling the onChange event using the syntax below: The code snippet ...

Setting the default type of an array in props in Vue 2 is a common need for many developers

My Vue component relies on an array of objects as a prop and I always make use of prop validation, especially for setting default values. In this case, my current setup is: props: { items: Array } However, I would prefer it to resemble something lik ...

AngularJS 2: Updating variable in parent component using Router

My current app.component looks like the following: import { Component, Input } from '@angular/core'; import {AuthTokenService} from './auth-token.service'; @Component({ selector: 'app-root', templateUrl: './app ...

What is the method to retrieve the ID name of an HTML tag based on its value?

Is there a way to determine the ID of an HTML tag based on its content? For example, if I have the following textboxes: I need to identify the id with the value "A2" So the expected result is id=option2 because its value is A2 <input type="text ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

The Node.js Express Server runs perfectly on my own machine, but encounters issues when deployed to another server

I've encountered a strange issue. My node.js server runs perfectly fine on my local machine, but when I SSH into a digital ocean server and try to run it there, I get this error. I used flightplan to transfer the files to the new machine. deploy@myse ...

Eliminating bottom section in HTML/CSS

I've got this code snippet: new WOW().init(); /* AUTHOR LINK */ $('.about-me-img img, .authorWindowWrapper').hover(function() { $('.authorWindowWrapper').stop().fadeIn('fast').find('p').addClass('tr ...

Sails.js: Issue with unintended premature sending of 200 response before desired response is sent

While working with Sails.js version 1.2.3, I encountered an issue where I was unable to send data from a file as a response to a GET request over HTTP or WebSockets. It seems that regardless of whether I access the file synchronously or asynchronously in t ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Is it best practice to initialize loaded scripts before the JQuery .load callback is called or should it be done after the .ready callback in the loaded script?

When I click a button in my main document, I load the content of a specific div using jQuery: $("#my_div").load(function() { alert("Content Loaded"); }); The loaded content contains a script: <script> alert("Initial Alert from External Script" ...

"Discover the Step-by-Step Guide to Launching Fresh Content or Code in the Current Tab and

I have a webpage with multiple tabs, each representing different content. Now, I want to create a functionality where if a user clicks on the "Home" tab, they are prompted to enter a password (e.g., 1234). Upon entering the correct password, the user shoul ...

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

A problem arises when trying to showcase the content in a responsive manner on the hamburger menu, particularly when viewing on mobile

As a newcomer to web development, I decided to challenge myself by building an E-Commerce website to enhance my skills. To ensure mobile responsiveness, I opted for a hamburger menu to hide the navbar content. However, despite resizing working flawlessly, ...

From Vanilla Javascript to ES6 Spread Operator

I recently incorporated a script into my project that utilizes the ES6 spread operator to extract parameters from the URL. However, I encountered an issue when I realized that the project does not support ES6 syntax. While it is straightforward to apply t ...

What is the best way to handle code versioning using Django, Angular2, and Webpack?

Currently, I am utilizing Django in conjunction with Angular 2 and Webpack. Within Django, I have set up a URL to display my application at http://example.com/user/beta. Initially, my index.html file is rendered, which contains my Angular 2 components. Wit ...

Error occurred in Flask due to request names being dynamically generated using JavaScript

My current project involves creating an app that calculates transit projections based on input years and other variables. I've written a JavaScript script where users can add new types of vehicles, each generating a unique div with specific ids and na ...