Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include:

  • An ID (obtained from the product URL using a function)

  • A color (retrieved through an event listener)

  • A quantity (also obtained through an event listener)

I already have a function that allows me to store objects locally using an array:

function addedToCart(productObject) {
  let listOfProducts = getProducts();
  listOfProducts.push(productObject);
  registerProducts(listOfProducts);
}


function getProducts() {
  let listOfProducts = localStorage.getItem("listOfProducts");
  if (listOfProducts == null) {
    return [];
  } else {
    return JSON.parse(listOfProducts);
  }
}

function registerProducts(listOfProducts) {
  localStorage.setItem("listOfProducts", JSON.stringify(listOfProducts));
}

In addition to this, I have implemented 3 event listeners:

  1. To detect when the user selects a color option and capture its value
  2. To track changes in the input field for quantity and retrieve its value
  3. To respond to the user clicking on the "Add to cart" button

Below is my JavaScript code:

... (JavaScript code omitted for brevity) ...

The issue I am facing is that redundant object instances are added to the array when the user clicks the "Add to cart" button multiple times or changes the quantity before adding to the cart.

[{id: "107fb5b75607497b96722bda5b504926", color: "White", quantity: "1"},…]
0: {id: "107fb5b75607497b96722bda5b504926", color: "White", quantity: "1"}
1: {id: "107fb5b75607497b96722bda5b504926", color: "Blue", quantity: "1"}
2: {id: "107fb5b75607497b96722bda5b504926", color: "Blue", quantity: "1"}
3: {id: "107fb5b75607497b96722bda5b504926", color: "Blue", quantity: "2"}

My aim now is to devise a function to compare and eliminate redundant objects in the array based on the ID, color, and quantity properties. This function should follow specific conditions outlined above.

If you need further clarification or have any suggestions regarding my code, please feel free to share. Your assistance is greatly appreciated.

Answer №1

To handle adding products to the cart efficiently, you can use the following JavaScript function:

function addToCart(product) {
  let productList = getProducts();
  productList = productList.filter(({productId, color}) => {
    return !(productId == product.productId && color == product.color);
  });
  productList.push(product);
  updateCart(productList);
}

This function removes any existing entry with the same productId and color as the new product being added, ensuring that only unique items are in the cart. Quantity is not considered when determining uniqueness, as the focus is on the product characteristics.

Answer №2

After much searching, I finally came across a resolution:


  const checkProducts = (productToCheck, productsArray) => {
    let foundProduct = productsArray.find((product) => { 
    const {id, color} = productToCheck;

   product.id === id && product.color === color
    }); 
  
    if(foundProduct){
      foundProduct.quantity = Number(productToCheck.quantity);
    }else{
      productsArray.push(productToCheck);
    }
  }

Answer №3

Here is a solution for removing redundant objects from an array by passing it to a function.

The logic involves iterating through the array in reverse order, checking for duplicate objects based on id and color.

  • If a duplicate object with the same id, color, and quantity is found, or an object with the same id and color but different quantity, it is considered redundant and removed.

After the loop, any undefined indexes are cleaned up to tidy the array.

An efficient way to implement this code is to check against the last added object when adding new objects.

const arr = [{id : 1, color : "black", quantity: 1}, 
           {id : 1, color : "black", quantity: 1},
           {id : 1, color : "black", quantity: 2},
           {id : 2, color : "black", quantity: 1}];
           
function getRidOfRedundant(arr) {
    let newArr = [...arr] //creating shallow copy of arr
    let compare = newArr.map(x => x.id + x.color);
    for (let i = 0; i < compare.length; i++) {
        if(compare.includes(compare[i], i + 1)) {
            delete (newArr[i])
        }

    }
    return newArr.filter(x => x !== undefined)
}

console.log(getRidOfRedundant(arr))

Another approach is to handle redundant objects during creation. You can have a constructor function that replaces duplicates in the array based on id and color.

You could also extract the logic into a separate function that finds the index of the redundant object and overwrites it with the new object.

class Product {

   static memory = [];
   static objects = []

   constructor(id, color, quantity) {
       this.id = id;
       this.color = color;
       this.quantity = quantity;

       if (Product.memory.includes(id + color)) {
           Product.objects[Product.memory.indexOf(id + color)] = this;
       } else {
           Product.memory.push(id + color);
           Product.objects.push(this);
       }
   }
}

new Product(id, color, quantity)

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

Is it possible to trigger JavaScript after loading a page in jqTouch with AJAX?

Similar to the kitchensink demo, I have successfully used jqtouch to call external .html pages into the index page. One of these external pages contains a video that is being played using sublime player. Everything is pretty basic so far, but my challenge ...

What is the best way to target a class within a span using CSS?

I need help with hiding an icon from the mobile menu. I am unsure about how to target this specific class within the menu structure. <a class="funiter-menu-item-title" title="Nieuw">Nieuw<span class="icon fa fa-chevron-down"></span>< ...

Unexpected Results from WordPress Ajax Request

Currently, I am utilizing the snippets plugin in conjunction with Elementor. To implement an ajax function as a snippet, I have set it up like so: add_action( 'wp_ajax_get_slug_from_id', 'get_slug_from_id' ); add_action( 'wp_ajax_n ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

What could be causing my Apollo useLazyQuery to be triggered unexpectedly within a React hook?

import { useLazyQuery } from '@apollo/client'; import { useEffect, useState } from 'react'; import { ContestSessionResponseInfoObject, GetSessionDocument, HasAccessToRoundDocument, } from '@/graphql/generated/shikho-private- ...

Obtaining the result from within the .then() block

Through the utilization of Google's API, I am successful in retrieving and displaying nearby places on the console. router.get('/', function (req, res, next) { // Locating nearby establishments googleMapsClient.placesNearby({ ...

Troubleshooting: Next JS 13/14 - Server component failing to update data upon revisiting without requiring a refresh

After attempting to retrieve the most recent liked items from a server component in next, I noticed that the data only displays when manually refreshing the page. Even when I navigate away and return, the data is not refetched automatically - however, usin ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

Step-by-step guide on permanently assigning a value in Node.js

I recently started working with node js and I am facing an issue where I need to save an id in a global variable that is required in multiple functions. However, every time the server restarts, the variable gets emptied. Is there a way to persist this va ...

What is the best way to locate the closest points using their positions?

I have a cluster of orbs arranged in the following pattern: https://i.sstatic.net/9FhsQ.png Each orb is evenly spaced from one another. The code I am using for this setup is: geometry = new THREE.SphereGeometry(1.2); material = new THREE.MeshPhongMateri ...

Selenium-webdriver is having trouble locating an element through the CSS selector

I encountered an issue while using selenium-webdriver in JavaScript to input a value into a field. Here is my test.js code: async () => { let driver = await new webdriver.Builder().forBrowser("chrome").build(); try { await driver.get("http://te ...

A sophisticated approach to implementing a search functionality within a complex JSON structure containing nested arrays using JavaScript

Searching for data in JSON format: { "results": { "key1": [ { "step": "step1", "result": "pass" } , { "step": "step2", "result": "pending" } ...

Ways to invoke external jQuery functions within Angular applications

In the midst of working on an Angular CLI Project, I find myself needing to incorporate some jQuery functionalities. To accomplish this task, I have added the necessary JavaScript files in the angular.json configuration: "scripts": [ "node_modules/jq ...

What mechanism enables the scores on this sports ticker to refresh automatically without relying on ajax calls?

While browsing scores on , I found myself intrigued by the way they update their scores without using ajax calls or iframes. It's a mystery to me how this functionality is achieved. Can anyone shed some light on how it works? ...

What is the best way to enable the delete function exclusively for users who are logged in?

I am currently working on implementing a delete function in JavaScript that will remove a MySQL row if and only if it was created by the user who is currently logged in. This means that users cannot delete rows they did not create. Below is the progress I ...

Utilizing third-party modules/functions across multiple classes

Seeking advice on sharing 'functions' between classes. Scenario: All of my code is consolidated in one file I am utilizing python-daemon to convert my script into a daemon This involves a class (Doorcamdaemon) for initialization and executi ...

Animating an image inside a bordered div

I'm attempting to create an animated effect where an image moves randomly within the boundaries of a div container. While I've come across solutions for animating within borders, none have specifically addressed keeping the image inside the div. ...

How can data be sent to an AJAX request using jQuery?

Every time I attempt to send data through ajax, it doesn't seem to pass the data along. $('#savenew').click(function () { var user = <?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data: user, su ...

Are You Able to Develop a Floating Window That Stays Persistent in JavaScript?

Looking to create a persistent floating window in a NextJS 14 app. This window needs to remain on top, even when navigating between browser windows. Want it to stay visible even when the browser window is minimized, like a Picture-In-Picture feature. Mos ...

What could be causing my jQuery switch not to function on the second page of a table in my Laravel project?

Having an issue with a button that is supposed to change the status value of a db column. It seems to only work for the first 10 rows in the table and stops functioning on the 2nd page. I'm new and could really use some help with this. Here's the ...