How to remove every instance of an item in an array based on its unique identifier using JavaScript

Is there a way to clean up an array of objects by removing duplicates with the same id? In this case, I only want to keep the object with id 1.

This is my approach:

let data = [{
    "selected": true,
    "id": 3,
    "ProductName": "Aniseed Syrup",
    "SupplierID": 1,
    "CategoryID": 2,
    "QuantityPerUnit": "12 - 550 ml bottles",
    "UnitPrice": 10,
    "UnitsInStock": 13,
    "UnitsOnOrder": 70,
    "ReorderLevel": 25,
    "Discontinued": false,
    "Category": {
      "CategoryID": 2,
      "CategoryName": "Condiments",
      "Description": "Sweet and savory sauces, relishes, spreads, and seasonings"
    }
  },
  {
    "selected": true,
    "id": 3,
    "ProductName": "Aniseed Syrup",
    "SupplierID": 1,
    "CategoryID": 2,
    "QuantityPerUnit": "12 - 550 ml bottles",
    "UnitPrice": 10,
    "UnitsInStock": 13,
    "UnitsOnOrder": 70,
    "ReorderLevel": 25,
    "Discontinued": false,
    "Category": {
      "CategoryID": 2,
      "CategoryName": "Condiments",
      "Description": "Sweet and savory sauces, relishes, spreads, and seasonings"
    }
  },
  {
    "selected": true,
    "id": 1,
    "ProductName": "Aniseed Syrup",
    "SupplierID": 1,
    "CategoryID": 2,
    "QuantityPerUnit": "12 - 550 ml bottles",
    "UnitPrice": 10,
    "UnitsInStock": 13,
    "UnitsOnOrder": 70,
    "ReorderLevel": 25,
    "Discontinued": false,
    "Category": {
      "CategoryID": 2,
      "CategoryName": "Condiments",
      "Description": "Sweet and savory sauces, relishes, spreads, and seasonings"
    }
  }
]


let data1 = data.filter(item => {
  return _.isEqual(data.lastIndexOf(item.id), data.indexOf(item.id))
})

console.log(data1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

The result remains unchanged. Ideally, I would like to have an array containing just the object with id 1.

I'm open to suggestions on how to achieve this goal.

P.S: Utilizing lodash is also an option.

Answer №1

Is it possible that this lodash method can effectively remove all duplicate values from the array?

_.uniqBy(array,'id')

Answer №2

If you want to efficiently keep track of unique IDs with their repetition count, you can utilize an object. Simply iterate over the array once more and include only those entries in the final output whose count is equal to 1.

let data = [{"selected": true,"id": 3,"ProductName": "Aniseed Syrup","SupplierID": 1,"CategoryID": 2,"QuantityPerUnit": "12 - 550 ml bottles","UnitPrice": 10,"UnitsInStock": 13,"UnitsOnOrder": 70,"ReorderLevel": 25,"Discontinued": false,"Category": {"CategoryID": 2,"CategoryName": "Condiments","Description": "Sweet and savory sauces, relishes, spreads, and seasonings"}},{"selected": true,"id": 3,"ProductName": "Aniseed Syrup","SupplierID": 1,"CategoryID": 2,"QuantityPerUnit": "12 - 550 ml bottles","UnitPrice": 10,"UnitsInStock": 13,"UnitsOnOrder": 70,"ReorderLevel": 25,"Discontinued": false,"Category": {"CategoryID": 2,"CategoryName": "Condiments","Description": "Sweet and savory sauces, relishes, spreads, and seasonings"}}, {"selected": true,"id": 1,"ProductName": "Aniseed Syrup","SupplierID": 1,"CategoryID": 2,"QuantityPerUnit": "12 - 550 ml bottles","UnitPrice": 10,"UnitsInStock": 13,"UnitsOnOrder": 70,"ReorderLevel": 25,"Discontinued": false,"Category": {"CategoryID": 2,"CategoryName": "Condiments","Description": "Sweet and savory sauces, relishes, spreads, and seasonings"}}]
let tracker = {}

data.forEach(({id}) => {
  tracker[id] = tracker[id] || 0
  tracker[id]++
})

const final = data.filter(({id}) => tracker[id] === 1 )

console.log(final)

Answer №3

Avoiding the use of a library, ES6 can handle time complexities at O(n) efficiently. It is also suggested to normalize objects within an array based on their IDs for quicker lookups.

As an illustration, I have included a third object with the ID: 4 to exemplify this code:

let data = [
  {"selected": true,"id": 3,"ProductName": "Aniseed Syrup","SupplierID": 1,"CategoryID": 2,"QuantityPerUnit": "12 - 550 ml bottles","UnitPrice": 10,"UnitsInStock": 13,"UnitsOnOrder": 70,"ReorderLevel": 25,"Discontinued": false,"Category": {"CategoryID": 2,"CategoryName": "Condiments","Description": "Sweet and savory sauces, relishes, spreads, and seasonings"}},
  {"selected": true,"id": 3,"ProductName": "Aniseed Syrup","SupplierID": 1,"CategoryID": 2,"QuantityPerUnit": "12 - 550 ml bottles","UnitPrice": 10,"UnitsInStock": 13,"UnitsOnOrder": 70,"ReorderLevel": 25,"Discontinued": false,"Category": {"CategoryID": 2,"CategoryName": "Condiments","Description": "Sweet and savory sauces, relishes, spreads, and seasonings"}}, 
  {"selected": true,"id": 4,"ProductName": "Aniseed Syrup","SupplierID": 1,"CategoryID": 2,"QuantityPerUnit": "12 - 550 ml bottles","UnitPrice": 10,"UnitsInStock": 13,"UnitsOnOrder": 70,"ReorderLevel": 25,"Discontinued": false,"Category": {"CategoryID": 2,"CategoryName": "Condiments","Description": "Sweet and savory sauces, relishes, spreads, and seasonings"}}]

const deduped = data.reduce( (acc, obj ) => {
  // restructure id from each object
  const {"id" : id}  = obj
  if ( acc[id] ) {
    return acc
  } else {
    return { ...acc, 
            [id]: obj
          }
  }
}, {})


The output in 'dedupe' will be organized by ID:

{ 3: 
   { selected: true,
     id: 3,
     ProductName: 'Aniseed Syrup',
     SupplierID: 1,
     CategoryID: 2,
     QuantityPerUnit: '12 - 550 ml bottles',
     UnitPrice: 10,
     UnitsInStock: 13,
     UnitsOnOrder: 70,
     ReorderLevel: 25,
     Discontinued: false,
     Category: 
      { CategoryID: 2,
        CategoryName: 'Condiments',
        Description: 'Sweet and savory sauces, relishes, spreads, and seasonings' } },
  4: 
   { selected: true,
     id: 4,
     ProductName: 'Aniseed Syrup',
     SupplierID: 1,
     CategoryID: 2,
     QuantityPerUnit: '12 - 550 ml bottles',
     UnitPrice: 10,
     UnitsInStock: 13,
     UnitsOnOrder: 70,
     ReorderLevel: 25,
     Discontinued: false,
     Category: 
      { CategoryID: 2,
        CategoryName: 'Condiments',
        Description: 'Sweet and savory sauces, relishes, spreads, and seasonings' } } }

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

Passing a portion of a StringArray to the next Activity by clicking on a ListItem:

In Activity1, I have a ListView with 10 items. When I click on an item, I want to pass a portion of a StringArray to my next Activity and bind it to a GridView using an ArrayAdapter. First Issue: I'm unsure how to pass data to the next Activity based ...

Storing the state of web applications in AJAX applications

How can the application state be maintained across requests for thick JavaScript clients? In addition to client managed cookies and descriptive URLs, are there any other methods? Please note that by clients I am referring to thick JavaScript clients. The ...

What is the top choice for creating a cutting-edge front-end web module?

Which generator or scaffold is recommended for creating a contemporary front-end web module using npm/webpack? ...

What is the best way to add a property and its value to objects within an array, especially those which do not currently have that specific property?

My goal is to: Iterate through the peopleData array, add a property named 'age' and assign it a value of '-' for any objects in the array that do not have the key 'age' const peopleData = [ { name: "Ann", age: 15, email: ...

Is there a way to extract information from the HTML source code of an external website and display it in my application?

Seeking a method to search an external URL for content that matches "title" and then display the results on my HTML page using Javascript. Despite my efforts with Javascript, I have not come across any resources that address this issue. Could it be that I ...

Contrasting the utilization of Angular $scope dependency with independent usage

As I delve into Angular, there's something that puzzles me. Being a newcomer to Angular, I recall a tutorial where they employed this syntax for applying properties to a controller's scope: app.controller('someCtrl', function(){ ...

The behavior of a fixed position in Flexbox varies when comparing Chrome to Safari and Firefox

In Chrome, the following code works as expected, with the list element positioning itself at the very left of the .PageContainer when scrolling down. However, in Safari and Firefox, the list element positions itself just after the logo. Are there any CSS r ...

Unresolved styles in React component linked to styles.css file

As I dive into creating a registration page in ReactJS, I encounter a frustrating issue with my styles not applying correctly from the styles.css file. Let's take a look at my RegisterPage.jsx component: export default function RegisterPage() { ret ...

Leveraging numerous identifiers in jQuery

I created a small jQuery script to check if the input box value is greater than 5, but I have two tags with IDs and only one of them seems to be working. <div id="register"> <form id="register"> <input id="first" type="text" /> <a ...

An array in Numpy that holds a nested array with a distinct data type

I am trying to replicate the result of a piece of code that I don't have access to. This code generates a nested structure of numpy arrays and lists. Desired outcome: array([array([[0]], dtype = uint8)], dtype = object) Current input: np.array([np.a ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Trigger a click event on a dynamically loaded button

Here's a unique twist to the usual discussions on this topic. I have a dynamically loaded button in my HTML, and I've saved the selector for it. Later on in my code, I need to trigger a click event on this button programmatically. The typical $(& ...

When using Javascript, you can expect to receive a modified structure that is different from

I am dealing with an array of objects that have the following structure: const data: [ { id: 21786162, label: "cBTC 2021-06-25 Put $50,000.00", active": true, type: "put", strike_price: 5000000, date_live: "2019-11- ...

When utilizing AngularJS, a parse error is triggered by array[ {{value}} ], but I prefer to overlook it

Within the controller, I have a selection list that is displayed like this: <select class="input form-control" id="animationTime" ng-options="item as item.label for item in aniCon.timeOptions track by item.id" ng-model="aniCon.popupTime" ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

"Encountered a type error: The .join method is not recognized as a function

Hello everyone, I've encountered an issue that has me a bit stumped. I recently took over a project and found a problem in which the previous developer was attempting to join an array of strings. Unfortunately, when I try to build the project, I keep ...

Toggle the checkbox to either select or deselect the value

I am attempting to toggle the value of a checkbox. When checked, the value should be set to active, and when unchecked, it should be set to disabled. The current code successfully changes text based on the checkbox status, but the issue is that the value ...

What is the best way to utilize JSON.stringify for substituting all keys and values?

In my current project, I am exploring how to leverage the replacer function argument within JSON.Stringify in JavaScript to alter the word case (toUpper / toLower case). The challenge I am facing is that my JSON data is not simply key:value pairs; some val ...

Utilizing ASCX to trigger JavaScript functions within an ASPX page

I created a user control named MyListSelect.ascx that contains a list of radio buttons... <%@ Control Language="C#" %> <select> <option disabled selected>Select Options</option> <option> option 1 </opti ...

Event follows activation of trigger click

I've already gone through this post on Stack Overflow about triggering an action after a click event, but none of the solutions I've tried so far have worked. Let's say I have a menu on my webpage like this: <ul class="nav nav-tabs"&g ...