What is the best way to remove duplicate objects from an array?

I have come across multiple resources discussing the deletion of duplicate values in objects, such as this, this, this... However, all these examples focus on simple objects whereas my scenario involves more "complex" data.

In my case, I have an array where each index contains values along with an embedded object. To illustrate this, consider the following simplified example:

var data = [
  {
    "name": "Kyle",
    "item": [
      {
        "id": 1,
        "name": "name1"
      },
      {
        "id": 2,
        "name": "name2"
      },
      ...
    ]
  },
  ...
]

As seen in the example above, there are duplicate values inside the `item` objects that I would like to eliminate.

One approach I considered was creating a copy of my list and using methods like `forEach`, `map`, or `filter`, but I'm unsure about how to proceed with this.

Here is an attempt that did not yield the desired result:

let dataCopy = data;

dataCopy.forEach(dataItem => {
  // logic here
})

The desired output should resemble:

var data = [
  {
    "name": "Kyle",
    "item": [
      {
        "id": 1,
        "name": "name1"
      },
      {
        "id": 2,
        "name": "name2"
      },
      ...
    ]
  },
  ...
]

If anyone has insights on how to achieve this, I would greatly appreciate the assistance.

Answer №1

To achieve this, use a straightforward combination of forEach and filter:

data.forEach(element => {
    element.item = element.item.filter((item, index, self) => {
        return index === self.findIndex(itemToFind => itemToFind.id == item.id)
    });
});

Answer №2

Utilize the Array.map() method to iterate through the array and apply a unique function to each item sub-array:

const data = [{"name":"Kyle","item":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},{"id":3,"name":"name3"},{"id":2,"name":"name2"},{"id":3,"name":"name3"}]},{"name":"Liza","item":[{"id":1,"name":"name1"},{"id":1,"name":"name1"},{"id":2,"name":"name2"}]},{"name":"John","item":[{"id":1,"name":"name1"},{"id":1,"name":"name1"},{"id":4,"name":"name4"},{"id":4,"name":"name4"},{"id":2,"name":"name2"}]},{"name":"Melissa","item":[{"id":2,"name":"name2"}]}];

const uniqueById = arr => Object.values(arr.reduce((r, o) => ({
  [o.id]: o,
  ...r
}), {}));

const result = data.map(o => ({
  ...o,
  item: uniqueById(o.item)
}));

console.log(result);

Answer №3

If you want to remove duplicates from a collection, you can create a utility function and then use it with the map method like this:

const removeDuplicates = (array, key) => {
  return Object.values(array.reduce((acc, item) => ({ ...acc, [item[key]]: item }), {}));
};

data.map((person) => ({ ...person, items: removeDuplicates(person.items, 'name') }));

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

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...

Learn the step-by-step process of cropping and zooming an image using the react-image-crop

I am looking to implement zooming and cropping functionality for an image using react-image-crop instead of react-easy-crop. Currently, the cropping does not take into account the zoom level set by ReactCrop's scale property. I want to be able to zo ...

Challenges in finding solutions from the generated results

I'm relatively new to Java and I'm struggling to prepare for an upcoming exam. One of the questions asks to explain the exact output generated by the given code: public class Lab7Experiment extends JApplet { int x=3, y=-3, z=5; int someV ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

Making a reference to the parent loop within a nested loop

I have a specific goal in mind. I have two tables in my database - 'regions' and 'distributors', both containing a region_id column. My objective is to achieve the following: 1) Iterate through the 'regions' table, creating a ...

Enable the expansion of a div by dragging and dropping an image onto it

Take a look at this fiddle. In this fiddle, I am able to drag and drop images onto the .drop-zone. However, I would like to enhance it so that when I drag an image onto it, the .drop-zone div expands to where I place the image. It's okay if the expand ...

Substitute the colon in JavaScript prior to submitting the form

I am currently working on a text input search field where I want to automatically add an escape backslash to any colon entered by the user. Below is the code snippet I have implemented so far: <form role="form" action="..." method="get"> <div ...

Creating a Commentary System in VueJS Similar to Medium

One feature that I admire in Medium is their commenting interface, which allows users to highlight specific portions of an article and leave comments. I am interested in integrating a similar commenting feature into a VueJS application. While researching ...

Display information in a pop-up window after loading data through an AJAX request and retrieving the relevant data from

I have encountered a problem that I cannot seem to resolve. In my database, I have users with expiration dates for their passports. My goal is to display a popup message for all users who have only 3 days left until their passport expires upon login. What ...

Keeping HTML and JS Variables in Sync for Dynamic Updates

Next to a number input, there are minus and plus buttons. Below these buttons, there is a "buy now" button that grabs values from the HTML and passes them to the href URL. How can I update the quantity in the href URL every time I click the minus/plus butt ...

Navigating through a jQuery array while utilizing the $.inArray method

Below is an example of my Array that I am working with, retrieved from a successful jQuery .post call: data = JSON.parse(data); $(".chk_permission_").each(function() { if ($.inArray($(this).val(), data)) { $(thi ...

The operation was computed twice

Below is an example: test.html <!DOCTYPE html> <html ng-app ng-controller="AppController"> <head> <script type="text/javascript" src="angular.js"></script> <script type="text/javascript" src="script1 ...

Using Python's list comprehension to populate a 2D array from Excel data results in only one column being displayed

I need help with reading an Excel range into a Python array. I am using Python 3.5 on Windows. The data in the Excel range is as follows: 2 2 0.833333333 1 2.166666667 2 0 0 1 0 1 1 1.5 1.1666 ...

Check Image Dimensions prior to Image Loading

I've been working with JQuery Masonry and would like to incorporate Lazy Load using a WordPress plugin to load images only when they come into view. The issue I'm facing is that when Lazy Load is used, the masonry elements don't recognize t ...

Use JavaScript to dynamically change the value of an HTML input field based on the contents of a <li> list item

On my HTML page, I am dynamically creating <li> elements using an Autocomplete API. As you type in the input box, the API suggests the Website logo, website name, and website URL within the <li> elements. Currently, this functionality is workin ...

Incorporate a Variety of Elements onto Your Webpage

I have developed a custom tooltip plugin using JQuery, and I am implementing it on multiple A tags. Each A tag should have a unique tooltip associated with it, so I have the following code: var $tooltip = $("<div>").attr("id", tooltip.id).attr("cla ...

Utilize binary search to discover the overlapping elements between two sorted arrays

Learning Java has led me to some queries. One of them is about finding common elements in two sorted arrays using binary search. Unfortunately, the code I wrote for this purpose doesn't yield accurate results. import java.util.Arrays; public class Co ...

I'm having trouble getting my application to output to the console. What could be the issue?

In my cr-route.js file, I have a function that ensures the user is authenticated before displaying their name. module.exports = function (app, passport) { // ===================================== // HOME PAGE (with login links) ======== // == ...

Why is the oninput function in JavaScript not functioning properly?

After following a practical video tutorial step by step, I tried to implement the code provided (in HTML and JS) but nothing seems to be working! The code snippet from the tutorial includes: var $count = document.getElementById("count"), $textarea = ...

embedding js files into html with node.js

When it comes to messaging via websockets between a HTML5 client and server running on node.js, I decided to use JSON as the message format. To streamline this process, I created common javascript code that defines different message content types and trans ...