Eliminating Repetitions in Array of Objects by Filtering Out Objects with Matching Properties

I am currently working with an array of objects where I need to identify duplicates based on specific properties (first and last names). Below is my attempt at solving this issue:

The expected output should resemble:

[
  {first:"John", last: "Smith", id:"1234", dupes: [555,666]},
  {first:"John", last: "Jones", id:"333", dupes: []}
];

let arrayOfObjects = 
[
  {first:"John", last: "Smith", id:"1234", dupes: []},
  {first:"John", last: "Smith", id:"555", dupes: []},
  {first:"John", last: "Jones", id:"333", dupes: []},
  {first:"John", last: "Smith", id:"666", dupes: []}
];


arrayOfObjects.forEach(record => {
  arrayOfObjects.forEach(rec => {
  if(record.first == rec.first &&
      record.last == rec.last &&
      record.id !== rec.id){
        console.log("match found for: " + JSON.stringify(record) + " and: " + JSON.stringify(rec));
        
        record.dupes.push(rec.id);
        //probably need to remove something here
      }
  });
});

console.log(JSON.stringify(arrayOfObjects));

Answer №1

Initially, I would advise against using .map() if it's not for mapping purposes. In this case, I have replaced the use of .map with .forEach as it is a more suitable choice.

Additionally, your comment

//probably need to remove something here
is accurate - indeed, you need to remove an item. Specifically, the duplicate item "rec" that was recently identified. This action can be accomplished by employing Array#splice, which necessitates the index of the item to be deleted. Obtaining the index is straightforward by utilizing the second parameter of the .forEach() callback.

let arrayOfObjects = 
[
  {first:"John", last: "Smith", id:"1234", dupes: []},
  {first:"John", last: "Smith", id:"555", dupes: []},
  {first:"John", last: "Jones", id:"333", dupes: []},
  {first:"John", last: "Smith", id:"666", dupes: []}
];


arrayOfObjects.forEach(record => {
  arrayOfObjects.forEach((rec, index) => {
// get index ------------------^^^^^-->------------------>--------------v
  if(record.first == rec.first &&       //                              |
      record.last == rec.last &&        //                              |
      record.id !== rec.id){            //                              |
        record.dupes.push(rec.id);      //                              |
        arrayOfObjects.splice(index, 1) //<--- remove using the index --<
      }
  });
});

console.log(JSON.stringify(arrayOfObjects));

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

Problem arises with chai-http middleware when employing dynamic imports in chai 5.1.1 version

Currently, I am utilizing npm chai version 5.1.1 which has transitioned to supporting only imports and not requires. My use of dynamic imports has been successful so far. However, I have encountered an issue when incorporating the chai-http middleware with ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...

When using jQuery, the script will execute successfully only when running it chunk by chunk in the console, rather than running the

As I tidy up an html page, my main task is to remove anchor tags and keep the text nodes. To achieve this, I am enclosing all text nodes (without any surrounding elements) within the <asdf> tag. Additionally, I am deleting empty elements such as < ...

When attempting to render a base64 string in an <img> tag using ReactJS, an error message ERR_INVALID_URL is displayed

I am currently working on displaying server-generated images (specifically matplotlib graphs) in a ReactJS module without needing to save the files on the server. To achieve this, I decided to use base64 to create an image string. When it comes time to sh ...

Tips on displaying the menu only when scrolling through the webpage

Currently, my website has a right menu that causes overlap with the content on mobile and small devices. To address this issue, I am working on hiding the right menu when the page is stable. The plan is for the menu to appear as soon as the user starts sc ...

activate the button once valid input has been provided

How can I enable a button based on the amount entered? Let's say there is a minimum of 100 and a maximum of 200. If the user enters an amount below 100, display an error message and keep the button disabled. If the user enters an amount above 200, ...

Printing a React component using a button causes formatting related to className to be lost, while printing it inline preserves the formatting

I've hit a roadblock in trying to figure out the React and printing issue for the past week and a half, and it feels like I'm going in circles. Despite finding some helpful solutions on Stack Overflow, none of them seem to work completely for me ...

positioning the cursor at the end of a content-editable div

When working with a contenteditable div, I encountered several issues specific to FireFox. To address these problems, I found that appending a br tag to the end of the div was necessary. <div id="testDiv" contentEditable="true"> Hey, click the butt ...

Difficulty with Vue Router horizontal scrolling to hash functionality

My goal is to achieve horizontal scrolling of the viewport by using a button wrapped in a router-link that navigates to a vue component. I was successful in achieving this functionality using anchor tags: <a href="#about"> <button cl ...

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

The wordpress jquery dependency is failing to respond

After converting an HTML ecommerce template into WooCommerce, I am experiencing issues with the functionality. The Nivo slider and some other product features are not working properly. It seems like they are having trouble finding WordPress jQuery, even th ...

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

Using XSL variables in JavaScript code

I've noticed that there have been similar questions asked, but none of the solutions seem to help in my case. So, I have this variable named 'var': <xsl:variable name="var"> val </xsl:variable> Now, I want to use it like thi ...

Tips for transforming a JSON response into an array with JavaScript

I received a JSON response from an API: [ { "obj_Id": 66, "obj_Nombre": "mnu_mantenimiento_de_unidades", "obj_Descripcion": "Menu de acceso a Mantenimiento de Unidades" }, { "obj_Id": 67, "ob ...

Using a variable as a URL parameter in a jQuery ajax request: tips and tricks

$.ajax({ type:"POST", url:"hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table, contentType: "application/json; charset=utf-8", crossDomain:true, dataType:'jsonp', succe ...

Ways to make the background color white in Bootstrap 5

Can someone assist me in changing the background color of my portfolio to white? I attempted to use global CSS, but the black background on both sides of the page is preventing the change. return ( <> <Navbar /> <main className= ...

Maximize Rotation - JavaScript Rotation

Currently tackling a Codewars challenge. The task involves finding the maximum possible result after performing a rotation on a given number. This rotation is unique in that 'n' number of digits will remain fixed after each rotation, with &apos ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Tips for extracting the image URL from my JSON string

I am in possession of a json file that includes URLs for images, and I have come across something that seems to be a URL, which is encoded as: iVBORw0KGgoAAAANSUhEUgAAADYAAAAzCAMAAADrVgtcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6m ...

Tips for developing screen reader-friendly AJAX areas and managing updates to the DOM?

My interactive user process operates in the following manner: Users encounter a dropdown menu featuring a selection of cities. Upon picking a city, an AJAX request retrieves all buildings within that city and inserts them into a designated div (the AJAX ...