In the scenario where there are duplicate 'id' keys within the array of objects, what is the best method to remove the object with the duplicate key?

When there are duplicate 'id' keys among the objects in the array, how can you remove the object with the duplicated 'id'?

I attempted to use filter, map, and set methods, but none of them were successful. Since the array is not one-dimensional, I am unsure of the correct approach.

Original:

"category": {
    "key": 1,
    "order": 1,
    "list": [
        {
            "id": "12345",
            ...
        },
        {
            "id": "12345",
            ...
        },
        {
            "id": "67890",
            ...
        },
        
    ]
}

Desired Output:

"category": {
    "key": 1,
    "order": 1,
    "list": [
        {
            "id": "12345",
            ...
        },
        {
            "id": "67890",
            ...
        },
        
    ]
}

Answer №1

  • By utilizing the reduce function on the list, we are able to iterate over each item and determine if the accessed key has been visited using the keys parameter within the reduce method. If the key has not been visited, the object is added to a filtered array and the keys array is returned to ensure it remains updated.

const data = {
  "category": {
    "key": 1,
    "order": 1,
    "list": [{
        "id": "12345"
      },
      {
        "id": "12345"
      },
      {
        "id": "67890"
      },

    ]
  }
}
let filtered = [];

data.category.list.reduce((keys, currentObject) => {
  if (!keys.includes(currentObject.id)) { //checking if current oject id is present in keys or not
    // if not present than we will just push that object in 
    keys.push(currentObject.id);
    //getting filttered object
    filtered.push(currentObject);
  }
  return keys; //returning keys to update it
}, [])
data.category.list = filtered; //updating list
console.log(data);

Answer №2

Based on a helpful suggestion from @Nick

let myData ={
"category": {
    "key": 1,
    "order": 1,
    "list": [
        {
            "id": "12345"
        },
        {
            "id": "12345"
        },
        {
            "id": "67890"
        },
        
    ]
}
}


let uniqueData = myData.category.list.filter((obj,index,arr) => arr.findIndex(obj2 => obj2.id == obj.id) == index)
myData.category.list = uniqueData
console.log(myData)

Answer №3

To efficiently track unique ids, you can utilize a set in JavaScript:

const category = [{
  "category": {
    "key": 1,
    "order": 1,
    "list": [{
        "id": "12345",
      },
      {
        "id": "12345",
      },
      {
        "id": "67890",
      },

    ]
  }
}]
const z = category.map(elem => {
  const set = new Set()
  return {
    ...elem,
    category: {
      ...elem.category,
      list: elem.category.list.reduce((acc, curr) => {
        if (!set.has(curr.id)) {
          set.add(curr.id);
          acc.push(curr)
        }
        return acc;
      }, [])
    }
  }
});
console.log(z)

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

Some inquiries regarding the fundamentals of JavaScript - the significance of the dollar sign ($) and the error message "is not a function"

Teaching myself JavaScript without actually doing any explicit research on it (crazy, right?) has led to a few mysteries I can't quite crack. One of these mysteries involves the elusive dollar sign. From what I gather, it's supposed to be a con ...

An unexpected 'undefined' value is being added to a particular Web API request

I am encountering an issue in my Angular application where the word 'Undefined' is being appended to a specific WebAPI call, causing both registerUser and login requests to fail. Here are the problematic request URLs: Request URL: http://localho ...

Utilize HTML, AJAX, and JavaScript to retrieve the location of the current user and display markers for other users on a

I am attempting to display on a single map the current location of a user and markers for other users, whose locations are obtained through an ajax post. In essence, I am looking to merge the concepts from: Google Maps Geolocation Example with: Multiple ...

Transforming Lines with ThreeJS

I have created a rotating cube in ThreeJS that is made up of multiple particles. These particles belong to an array called 'particles' and are part of a group named 'group' which rotates around the origin on all axes (x, y, z). My goal ...

The XMLHttpRequest is displaying additional characters within its response

Upon completing an XMLHttpRequest(), I am receiving the unexpected output of "true↵↵↵". In my php file, all I have is echo json_encode(true); Can anyone shed some light on why this strange behavior is occurring? Thank you ...

Numerous points highlighted on the map

As I develop my application, I am working on setting up an event to automatically load data from a CSV excel file for display. My goal is to extract information from the Excel CSV file and use it to populate locations on a Google Map within my application ...

transmit information and documents to server using Axios

I am working on a project using ReactJs and I need to send data to a Laravel API using Axios. Here is the code snippet I have tried: export const send = (data, File) => { const formData = new FormData(); formData.append('media', File); ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

AJAX request made to a specific local directory, instead of the usual localhost

Currently, I am working on a project to create a database that can be filtered using various options. My approach was to keep it simple by using HTML for sliders and checkboxes, along with JavaScript/jQuery for filtering the results. This setup allows me t ...

Migration unsuccessful due to incompatible peer dependencies detected - Updating Angular to Version 12 was not successful

Currently in the process of upgrading my Angular v11 apps to Angular v12. Encountering an error while attempting to upgrade Angular packages: ng update @angular/core@12 @angular/cli@12 Error: Migration failed due to incompatible peer dependencies The pa ...

What is the best way to display a string state value in a React component?

I need assistance with displaying a state value that is in string format. Despite my efforts, I have not been successful in finding a solution and am feeling quite frustrated. Can anyone provide some guidance? ...

Categorize an array by their names using Jquery and present them as a list

I have a list of cities and their corresponding countries structured like the following: { "data": [ { "cityname": "Newyork", "countryname": "USA" }, { "cityname": "amsterdam", "countryname": "Netherland" },{ "cityname": "Washington", "country ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

JavaScript fails to focus on dynamically inserted input fields

Within my HTML template, there is an input element that I am loading via an Ajax call and inserting into existing HTML using jQuery's $(selector).html(response). This input element is part of a pop-up box that loads from the template. I want to set f ...

Dynamic visual content (map)

I'm currently working on creating an interactive image for my website where clicking on points A, B, C, ... N will reveal bubbles with images and text inside them. Would anyone be able to provide guidance on how to achieve this? Or direct me to resou ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

Encountering an unhandled runtime error while importing the Client component into the server component: The JSON format is invalid, with the error message stating "undefined"

I've been attempting to create a basic counter component that increments the count of a state variable when a button is clicked. To achieve this, I created a separate file named Counter.tsx and placed it in the components folder at the root of my next ...

Div scrolling allows for parallel viewing of PDFs in a side by side arrangement

I have two scrollable elements on my webpage: one positioned on the left side and the other on the right side. The left element is a regular div, while the right element is an object containing an embedded PDF. <object width="100%" height=&quo ...

Unlimited scrolling: Fetching additional data via an Ajax request?

I am working on setting up a table with infinite scroll functionality to showcase user information such as name, address, and email. To accomplish this, I began by importing the json-server package and creating an API endpoint using fakerjs in a separate f ...

Integration of elFinder with TinyMCE 4

Has anyone attempted to integrate elFinder into the latest version (4b1) of TinyMCE? The previous implementation seems to be not working. If you have any snippets or tips, please share. Thank you very much. ...