Verify the presence of identical items in the array

I have been attempting to identify any duplicate values within an array of objects and create a function in ES6 that will return true if duplicates are found.

arrayOne = [{
    agrregatedVal: "count",
    value: "Employee Full Name"
  },
  {
    agrregatedVal: "min",
    value: "Employee Full Name"
  },
  {
    agrregatedVal: "min",
    value: "Employee Full Name"
  },
  {
    agrregatedVal: "count",
    value: "Pay Date"
  },
  {
    agrregatedVal: "count",
    value: "Employee Full Name"
  },
  {
    agrregatedVal: "min",
    value: "Signature"
  },
  {
    agrregatedVal: "min",
    value: "Pay Date"
  }]
  
  

This is the JSON structure provided:

There are two duplicate objects as shown below:

{
  agrregatedVal: "min",
  value: "Employee Full Name"
}, {
  agrregatedVal: "min",
  value: "Employee Full Name"
}

The rest of the objects do not concern us, only the ones with identical values. If each object value is a duplicate of another object in the same array, the function should return true.

I attempted the following approach:

this.arrayOne = this.arrayOne.filter((thing, index, self) => {
  return index === self.findIndex((t) => {
    return t.agrregatedVal === thing.agrregatedVal && t.value === thing.value;
  });
});

However, it did not yield the desired result. How can I ensure that the function returns true when the value of each object matches that of another object?

Answer №1

Some key points to consider:

1) Checking for Duplicates :

I encountered an issue - how can I determine if the values of one object match the values of another object.

const dictionary = arrayOne.map((item, index) => {
  return item.aggregatedVal + ":" + item.value;
});

const hasDuplicate = dictionary.some(function(item, id){ 
     if(dictionary.indexOf(item) != id)
       return item;
});

console.log(hasDuplicate);

2) Removing Duplicates :

uniqueValues = [...new Set(arrayOne.map(a => a.aggregatedVal + "':'" + a.value))];

You can now reconstruct your object using these unique values

Answer №2

Give this code a shot:

const data = [{
    key: "apple",
    value: 10
  },
  {
    key: "banana",
    value: 15
  },
  {
    key: "apple",
    value: 20
  },
  {
    key: "orange",
    value: 12
  }]

function hasDuplicate(data) {
  const uniqueData = data.filter((item, index, self) => index === self.findIndex(i => i.key === item.key && i.value === item.value));

  return uniqueData.length < data.length;
}

console.log(hasDuplicate(data));

The function hasDupliecate will return true if there are any duplicates in the provided data array.

Answer №3

Removing duplicates from an array

Let's examine the following code snippet:

const initialArray = [
  {agrregatedVal: "count", value: "Employee Full Name"},
  {agrregatedVal: "min", value: "Employee Full Name"},
  {agrregatedVal: "min", value: "Employee Full Name"},
];

const dedupedArray = [
  ...new Set(initialArray.map(item => JSON.stringify(item)))
].map(itemJson => JSON.parse(itemJson));

console.log(dedupedArray);

  1. Each item in the original array is converted to a Json string
  2. The strings are added to a Set which automatically eliminates duplicates
  3. The unique Json strings from the Set are then transformed back into an array
  4. The objects are reconstructed from the strings

Function for detecting duplicate objects in an array

If you're looking to create a function that determines whether an object is a duplicate of another object within an array, consider this alternative approach:

const array = [
  {agrregatedVal: "count", value: "Employee Full Name"},
  {agrregatedVal: "min", value: "Employee Full Name"},
  {agrregatedVal: "min", value: "Employee Full Name"},
];

const isDuplicate = (itemA, array) => !!array.find(itemB => itemA !== itemB && JSON.stringify(itemA) === JSON.stringify(itemB));

console.log(isDuplicate(array[1], array))

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

Implementing JavaScript Code in TypeScript

Every JavaScript code should also be valid in TypeScript, but when attempting to run the following code snippet below, an error is triggered. Could someone convert this JavaScript code into TypeScript? Error: 20:9 - TS2531 Error: Object is possibly 'z ...

Encountering error code 128 while attempting to download npm packages

After attempting to install jspdf using the command npm install jspdf --save, I encountered the following error: npm ERR! code 128 npm ERR! Command failed: git submodule update -q --init --recursive npm ERR! error: waitpid for git-submodule failed: No chi ...

Leverage the key-value pairs in JSON to automatically suggest types within the function parameters

If we have data structured like this: { "key1": "hardcoded string", "key2": "another hardcoded string", } Imagine a function with 2 parameters where the first parameter should refer to key1 and the second to i ...

Troubleshooting issue with beforeEach in karma and Mocha after upgrading to Angular 4

Unique Context After verifying the successful "green" builds on the master branch, which utilizes angular-cli 1.0.0 and the older angular2 dependencies, my goal is to transition from angular2 to angular4. Issue Post Upgrade The application functions pr ...

Exploring Angular Testing with SpyOn

Apologies for my inexperience with Angular, but I am struggling with using spyOn in a unit test. In my unit test, there is a method on the component that calls service1, which in turn calls another service2. However, when I try to spyOn service1 in order ...

``There seems to be an issue with retrieving and displaying data in Ionic2 when using nav

I am facing an issue with displaying the data received from NavParams. I have used console.log() to confirm that I am getting the correct data, but for some reason, I am unable to display it on the new page. I suspect that there might be an error in how I ...

Angular - Mark all checkboxes on/off

My task involves implementing a specific functionality. I have three checkboxes, and when one is selected, I want the other two to be automatically selected as well. I am using a pre-built component to create these checkboxes. <form [formGroup]="d ...

Ways to fetch information from NGRX store in a linear manner

Struggling to handle NGRX's data access patterns effectively. Currently, I am retrieving data from my NGRX store in the following manner: logBooksAndAuthors() { const books$ = this.store.select(store => store.books); const authors$ = this.s ...

The click event triggered by the onclick clone/function may not always activate the click handler

As a newcomer in the JavaScript domain, I am encountering an issue where the first clone created after clicking 'add more' does not trigger my click me function. However, every subsequent clone works perfectly fine with it. What could be causing ...

What causes the createResource error to become undefined when it is refetched before being properly set?

How can I access and display the error property for a createResource? In this scenario, why is the error initially set to undefined before it is thrown? The logging shows that it first displays undefined for the error before eventually getting to line er ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Exploring methods for efficiently handling extensive XLSX files in a Node.js environment

Currently, I am utilizing the ts-xlsx library on the server side to read data. The process involves reading data from the frontend as a byte array using file-reader and then sending this byte array to a library to process the data. However, in cases where ...

Angular dynamic directive for displaying additional content or collapsing content based on user interaction

Here's the code snippet I have in an Angular 7 application to toggle the visibility of elements (Example): <ul> <li>Item 1</li> <li>Item 2</li> <li *ngIf ="hidden">Item 3</li> <li *ngIf ="hidden">It ...

Unable to simultaneously execute TypeScript and nodemon

Currently, I am in the process of developing a RESTful API using Node.js, Express, and TypeScript. To facilitate this, I have already installed all the necessary dependencies, including nodemon. In my TypeScript configuration file, I made a modification to ...

What is the best way to develop an Angular library with components in version 8 that can be seamlessly integrated into upcoming Angular versions such as 12, 13, and 14

Do I need to implement a new technique or setup in order to understand this? Can we use Angular elements as the only solution, or are there alternative approaches available? ...

Angular is set up to showcase every single image that is stored within an array

I am having trouble displaying the images from the "image_url" array using a for loop. The images are not showing up as expected. Here is the content of the array: image_url: [ 0: "https://xyz/16183424594601618342458.5021539.jpg" 1: "https://xyz/1618342459 ...

The functionality to disable the ES lint max length rule is malfunctioning

In trying to disable an eslint rule in a TypeScript file, I encountered an issue with a regular expression that exceeded 500 characters. As a result, an eslint warning was generated. To address this, I attempted to add an eslint comment before declaring th ...

Can anyone provide guidance on setting up systemjs to identify an app path specific to the environment?

I recently developed a web application using Angular and angular-cli. It works perfectly fine when running it with ng serve. Now, I have the task of deploying it on Tomcat. The catch is that it needs to be accessible through a different path because my We ...

Issue encountered while trying to run `npm install` on an angular-cli

I recently moved my angular-cli project with node modules to a new directory. Upon running npm install, I encountered the following warnings: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2838c85978e8 ...

Exploring the Wonderful World of Styled Components

I have a query regarding styled components and how they interact when one is referenced within another. While I've looked at the official documentation with the Link example, I'm still unclear on the exact behavior when one styled component refe ...