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

Navigating with Vue Router in a Nuxt JS vuex Store

In my app, I'm currently developing a login/register system using Firebase and Vuex for authentication and database management. Within Nuxt JS, I have implemented actions to create a user, log them in, and sign them out. After a successful registrati ...

Even though the onSubmit attribute is set to false in the HTML form, it still submits

I've been struggling with a form that just won't stop submitting, no matter what I do. I have checked similar questions on SO, but none of the solutions seem to work for me. It's frustrating because it's such a simple task. The reason w ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

storing a value in the browser's local storage

I am in the process of creating a new game that includes a high score feature. The idea is that when the current score surpasses the existing one stored locally, it will be replaced: localStorage.setItem('highScore', highScore); var HighScore = ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Encountering a problem with Nginx and WordPress where the admin-ajax.php is causing an issue when returning an AJAX result, leading to an error of Un

Currently, the issue is that everything runs smoothly on my Apache server, but when I switch to Nginx, an error is triggered with Uncaught SyntaxError: Unexpected token < Below is the function extracted from Functions.php function searchranges() { ...

Can CSS be used to automatically focus on a div element?

Can CSS be used to set autofocus on a div element? <div class="form-group" style="margin-left:10px"> <label for="organizationContainer" class="nmc-label">@Res.GroupStrings.CreateNewGroupOrganization</label> <div id="organiza ...

Leveraging various routes to access data with a shared VueJS 3 component

Could you please review this code snippet: It displays two routes that utilize the same component to fetch content from an API. Main.js const router = createRouter({ history: createWebHistory(), routes: [ { path: "/route1& ...

Utilizing jQuery AJAX to efficiently handle branching based on the result received

I've successfully set up my first AJAX call with jQuery. The only thing left to do is to check the result from the PHP page for any database errors and display an error message if necessary. Here's the current Javascript code: <script type=" ...

Organizing classes under namespaces in Node.js

Currently working on a project in node.js. I have several related classes that I want to organize in a subdirectory, with one class per file structured like this: lib/ main.js melons/ casaba.js cantaloupe.js carnegie.js I plan to us ...

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...

Importing D3 data from CSV files using the "%" symbol

I am trying to import a CSV file with the following data: Month, Ratio January, 0.19% February, 0.19% March, 0.19% April, 0.18% The current code snippet I'm using is as follows: d3.csv("month_ct.csv", function(d) { return { month: d ...

What strategies can I use to streamline this array update function code?

Looking to simplify my updated array function. The update function involves updating and comparing values in an array. The comparison will be done within the fruit_temp. For example, data in fruit_temp's fruit_db_id corresponds to an existing id in th ...

Is your JQuery Gallery experiencing issues with the next button function?

I'm working on developing a simple gallery using JQuery. The main concept is to have all image files named x.png (where x is a number), and the program will then add a number to the current one, creating x+1.png and so forth. Here's the code I ...

Disabling the current date on date pickers in material ui: A step-by-step guide

In my current React project, I am utilizing material-ui-date-pickers and need to prevent users from selecting today's date. This is important in the context of manufacturing products, managing expiration dates, and handling billing processes. Since a ...

Styling GeoJSON data in the React Leaflet mapping library can greatly enhance the

I successfully incorporated the leaflet map library into my react project. You can check it out here. I also created a geojson map component as shown below: class MapContainer extends React.Component { state = { greenIcon: { lat: 8.3114, ...

Exploring the ins and outs of HTML event handlers with JavaScript

When using events in your HTML and including a small amount of JavaScript, what is this called? Is it referred to as a "JavaScript attribute function," simply a "JavaScript attribute," or something else entirely? For example: <button onClick="locat ...

Can Backbone be used to retrieve a local JSON file?

I have a simple and validated local JSON file that I am trying to fetch using Backbone.js. Here is the snippet of Backbone.js code: MyModel = Backbone.Model.extend({ defaults:{ name: '', age: 0 } }); MyCollection =Backbo ...

What is the best way to incorporate tooltips in SVG?

My teacher wants me to display a tooltip on an SVG circle with links and information when we hover over it. They suggested using jQuery UI, but I've done extensive research and nothing has been able to assist me so far. ...

I am not getting any reply in Postman - I have sent a patch request but there is no response showing up in the Postman console

const updateProductInfo = async (req, res) => { const productId = req.params.productId; try { const updatedProduct = await Product.findOneAndUpdate({ _id: productId }, { $set: req.body }); console.log("Product updat ...