Is it possible to retrieve duplicate objects within the same array?

My array contains multiple objects.

arr = [
{name: 'xyz',
age: 13,
},

{name: 'abc',
age: 15,
},

{name: 'abc',
age: 15,
}]

I am seeking a solution to identify and remove duplicates in this array. Is it possible to achieve the removal of duplicated objects based on one key? For instance, deleting an object named "def" if its age matches another object's age?

arr = [
{name: 'xyz',
entry: 1,
age: 13,
},

{name: 'abc',
entry: 2,
age: 15,
},

{name: 'def',
age: 13,
entry: 3
}]

Answer №1

To accomplish this task, you can follow these steps:

  • Convert each element into an object that is key-sorted to ensure consistency in the order of key-value pairs.
  • Stringify the objects and store them in a Set() to keep only unique stringified objects.
  • Revert the Set() back to an array.
  • Parse each element in the array back into objects using JSON.parse().

const arr = [
  { name: "xyz", age: 13 },
  { age: 15, name: "abc" },
  { name: "abc", age: 15 },
]

const sortKeys = obj =>
  Object.fromEntries(
    Object.entries(obj).sort((keyValuePairA, keyValuePairB) =>
      keyValuePairA[0].localeCompare(keyValuePairB[0])
    )
  )

const res = Array.from(
  arr
    .map(sortKeys)
    .map(el => JSON.stringify(el))
    .reduce((set, el) => set.add(el), new Set())
).map(el => JSON.parse(el))

console.log(res)

References

Set

Object.entries()

Object.fromEntries()

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

Does utilizing this.someFunction.bind(this) serve a purpose or is it duplicative

As I analyze someone's code, I stumbled upon the following snippet: this.device_name.changes().onValue(this.changeName.bind(this)) My interpretation so far is that onValue requires a callback function, which in this case is this.changeName.bind(this ...

The issue with Ajax file upload is that it only processes the first file in the filelist array for

I am struggling with an issue while using jquery and materialize for asynchronous file upload and form submit. The code seems to work fine when I use get(0).files[0], but it only returns the first file at index [0]. However, when I attempt to loop through ...

How to match and merge two arrays of objects based on a shared value in JavaScript

let array1 = [{ "id": "lap-143240121", "position": 0 }, { "id": "lap-15040293", "position": 1 }, { "id": "lp-1504444", "position": 2 }, { "id": "lp-150440987", "position": 3 }] let array2 = [{ "id": "lap-143240121", "name": "name1" }, ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

Will a notification box appear upon submission indicating success or failure?

After the submit button is clicked, I need a pop-up box to display either a successful or failed message. Then confirm the message by clicking OK. Currently, I am seeing an "undefined" pop-up followed by a failed message pop-up. Can someone please assist m ...

Converting all numbers separated by commas to numbers separated by periods in a string using JavaScript

Imagine a scenario where you have a string containing numbers, such as, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text Your task is to replace the numbers with decimals instead of commas without altering anything else in the ...

Retrieve and dynamically load an entire webpage using AJAX

Although it's typically not recommended, I am interested in displaying the progress of a download on a heavy page to show the user when it's ready. Is there a way for me to track and display the actual progress of the download? Can I monitor how ...

Galleriffic 2.0: Enhancing Animation Queues

I'm currently exploring how to utilize the stop() function in order to halt the animation buildup within Galleriffic. This issue arises when swiftly and repeatedly mousing over the thumbnail images. While I understand that in a basic jQuery script, yo ...

Is it possible to have separate click functions for the onclick attribute and jQuery click handler on an anchor tag, instead of just calling one function through onclick?

Attempting to implement multiple click handlers for an anchor tag: one using the "Onclick" attribute handler and the other using a jQuery click handler. This excerpt is from my HTML file. <html> <head> <script src="http://code.jquery.com ...

Is Redux really the new trend in the world of action creators?

I am new to this. I'm a bit unsure, is it okay or silly to use the pattern below? import { createAction, handleActions } from "redux-actions"; const CHANGE_STATE = "appState/CHANGE_STATE"; export const changeState = createAction(CHANGE_STATE, (key, ...

Preventing the submission of form post values by using jQuery remote validation

     Within my form, I have incorporated two submit buttons (save & exit, next) and implemented remote email address duplication checks. Everything is functioning properly, however, upon submission of the form, I am unable to determine which specific s ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

Retrieve items from an array using indexes provided by a separate reference table

I am dealing with two different arrays. One array contains my data: var tab1 = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"]; ...

Utilizing Python to retrieve daily weather forecasts from the wunderground JSON API

Here is a query regarding extracting a single data point from a json file using the python json module The json response looks like this: { "response":{ "version":"0.1", "termsofService":"http://www.wunderground.com/weather/api/d/terms.htm ...

What is causing the form validation lines to not save and appear after I refresh the page?

Having trouble with the append element in my JavaScript code. Below is the JS file and the corresponding HTML file. JavaScript file: var ck_name = /^[A-Za-z0-9 ]{3,20}$/; var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*& ...

Discovering the process of extracting a date from the Date Picker component and displaying it in a table using Material-UI in ReactJS

I am using the Date Picker component from Material-UI for React JS to display selected dates in a table. However, I am encountering an error when trying to show the date object in a table row. Can anyone provide guidance on how to achieve this? import ...

How can I iterate through each element of MySelector in the callback function of jquery-ui's draggable function?

When using: jQuery(MySelector).dragabble( start: function( e, ui ) { } ) In the start function: The start event provides $(this) with the current dragged element from MySelector. How can I loop through each element in MySelector to apply additional code ...

ngResource/$resource injection was not done correctly

I am currently working on developing a client for an API, and I am encountering an issue with the $resource module not being correctly injected. Despite adding ngResource to the module and passing it into the factory declaration, I am facing an error when ...

Error encountered while loading JSON data: Anticipating comma delimiter

I am encountering an issue with a JSON file and here is my code snippet: import json x= '{ "receive_time": "2020-06-26T08:04:27+07:00", "services": "", "request_uri": "/", "request_body& ...

Creating a cutting-edge single page web application with the MERN stack: A comprehensive guide

After researching various articles on building dynamic apps with Express.js using technologies like EJS and Handlebars, I have decided that I want my web app to be dynamic and single page by utilizing React instead. My goal is to render templates and inse ...