Eliminate any duplicate items from the array containing objects

I've been struggling with this issue for a week now, hopefully someone here can help me out...

The application I'm working on was created using Laravel with Vue for the frontend.

Essentially, I have an array of objects that need to be sent to the backend to be stored in a database. The challenge lies in the fact that this is an editor and the page shouldn't reload every time a change is made. The data is retrieved using window.postMessage(), which seems to cause some lingering issues even after saving.

I've attempted to empty the array after calling the save function. Initially, it works fine because the array is empty, but from the third attempt onwards, some objects get duplicated and stored in the database.

Below is the code snippet:

saveNewSettings() {
   //ARRAY TO BE EMPTIED (DECLARED IN DATA OBJECT)
   /* this.newItems = [
                        { id="123", name="a", otherProps="someProps" },
                        { id="456", name="ab, otherProps="someProps" },
                        { id="789", name="c", otherProps="someProps" },
                      ]
   */
   //EMPTY ARRAY USED FOR COMPARISON
   // this.newlyCreatedItems = [];

   if ( !this.newlyCreatedItems.length ) {
      this.newlyCreatedItems = this.newItems;
   } else {
      for ( let i = 0; i < this.newItems.length; i++ ) {
          for ( let j = 0; j < this.newlyCreatedItems.length; j++ ) {
              if ( this.newItems[i].id == this.newlyCreatedItems[j].id ) {
                 this.newItems.splice( i, 1 );
              }
          }
      }
   }

   //SENDING INFO TO BACKEND SERVICE
   settingsService.save( this.newItems )
   .then(response => {
        //ACTION AFTER RESPONSE
   });
}

The function behaves correctly the first and second time, only saving new items without duplication. However, starting from the third time, duplicates start appearing in the database.

If more information is required, please feel free to ask. Thank you all in advance for your assistance.

Answer №1

Simple method using JavaScript:

const names = ["John", "Jane", "Jack", "Amy", "Mark", "Jane", "Emily"];
const uniqueNames = [];
names.forEach(name => {
    if(!uniqueNames.includes(name)){
        uniqueNames.push(name);
    }
});

Answer №2

You specified vue.js as the tag, but this issue seems to be more related to the JavaScript side. Essentially, you are performing a shallow copy of the newItems array into the newlyCreatedItems array, causing conflicts due to both referencing the same memory address.

To resolve this problem, you can use deep cloning by utilizing the structuredClone() method.

Check out the Live Demo below:

let newItems = [
  { id: "123", name: "a", otherProps: "someProps" },
  { id: "456", name: "ab", otherProps: "someProps" },
  { id: "789", name: "c", otherProps: "someProps" }
];

let newlyCreatedItems = [];

function saveNewSettings() {
  if (!newlyCreatedItems.length ) {
    newlyCreatedItems = structuredClone(newItems);
  } else {
    for ( let i = 0; i < newItems.length; i++ ) {
      for ( let j = 0; j < newlyCreatedItems.length; j++ ) {
        if ( newItems[i].id == newlyCreatedItems[j].id ) {
          newItems.splice( i, 1 );
        }
      }
    }
  }
}

saveNewSettings();

console.log(newlyCreatedItems);
console.log(newItems);

console.log('-------');

saveNewSettings();

console.log(newlyCreatedItems);
console.log(newItems);

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

Creating an expandable discussion area (part II)

After checking out this query that was posted earlier, I am interested in implementing a similar feature using AJAX to load the comment box without having to refresh the entire page. My platform of choice is Google App Engine with Python as the primary lan ...

What is preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

Delete entries in table based on user-provided criteria

Hello there, I'm new to this community and seeking some assistance. I am currently learning jQuery/Javascript and have encountered a problem that has me stumped. The issue arises with a table where rows are generated based on a user-selected number f ...

Encountering the error message "React child cannot be an object" while trying to map over an imported object referencing components

I have an array in a separate file that I import and iterate over in another component. One of the properties within this array, labeled component, actually refers to a different individual component. I am attempting to render this component, but I keep e ...

The data source is having trouble connecting to the updated JSON format due to issues with pagination

I'm utilizing pagination.js to fetch asynchronous data using the code below. $('#demo').pagination({ dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?&ap ...

Issue with Braintree drop-in form: Nonce string generation problem

I've encountered a peculiar issue while trying to utilize the dropin form from Braintree. Successfully integrating the form into a view, here's how it looks: <form id="createTransactionForm" method="post" action="#&qu ...

Tips for implementing a document ready function on a nested page within a larger full-page website

I am currently working on a website that utilizes fullpage.js, but the same principle applies to all single-page websites. I am trying to figure out how to implement the $(document).ready() function on a 'nested' page within the site. Since every ...

Tips on utilizing Ajax for updating the RenderBody() segment

Can anyone help me understand why my Ajax.ActionLink menu item is calling JavaScript twice when I try to use it for the second time? I simply want to update the RenderBody() after clicking on a menu item. _Layout.cshtml: ... <body> <div i ...

How can I fix the issue of the dropdown button extending the height of the navigation bar when clicked on?

Currently, I am working with the Laravel framework and aiming to incorporate a Bootstrap dropdown within a navbar without affecting its height when clicked. Preview image: https://i.sstatic.net/r9uhH.png Despite going through the documentation for both B ...

Switch the hue when altered

My document contains various input elements such as text, radio buttons, and checkboxes. I want each of these elements to change color when a change is made. This is the method I am currently using: $("document").on('click', 'change', ...

Using Vue3 and Vite: Is it possible to automatically convert Vue scoped styles from data-v attributes to hashed class names?

Could the scoped style in Vue.js transform to hashed classnames instead of using data-v attributes like this: <template> <div class="example">123abc</div> </template> <style scoped> .example { color: red; } </s ...

What is the best way to receive the information that was transmitted to me through a callback function?

While web development is not my strong suit, I have a question that might sound silly, so bear with me as I explain. Once the user selects their desired purchase, an API call is made to generate a trans_id and redirects them to the bank's payment pag ...

Having trouble executing a MongoDB query through Mongoose without using a REST API

Dealing with the Express router has been an uphill battle for me. While Mongoose models work seamlessly within routes, I've hit a roadblock when trying to utilize the models in other files without routes. Whenever I attempt to run the file containing ...

What causes the disparity in functionality between simple html and css in an Angular 2 project compared to a vanilla html website?

When incorporating the following html/css into a new Angular project created with Angular CLI using 'ng new ProjectName', I encountered issues. Despite adding the CSS to app.component.css or styles.css and the HTML to app.component.html, the Angu ...

Why is Socket.io functioning on localhost but fails to work once deployed to Heroku?

Sharing my socket server code: const io = require("socket.io")(8080, { cors: { // origin: "http://localhost:3000", origin: "https://mern-bubble.herokuapp.com", }, }); This is the client-side implementation: useEf ...

Adding to array using v-model

Just starting out with Vue.js, I'm delving into developing a shop application using Vue and Webpack. My product data is stored in a json file, and I am rendering them with the help of v-for. My goal is to have the ability to add products to a cart by ...

What is the best way to disable the click function for <a> tags that have a specific class?

I am dealing with parent navigation items that have children, and I want to prevent the parent items from being clickable. Here is an example of how they currently look: <a href="parent">Parent Item</a> Is there a way to select the <a> ...

Integrating Socket IO with Kubernetes

I am currently in the process of transitioning a socket io service from GCP (Google Cloud Platform) App Engine to a Kubernetes cluster. Everything is functioning properly on the GCP side with a single server instance and no replicas. The migration to Kuber ...

Utilizing JQuery to detect a combination of ctrlKey and mouse click event

Looking for assistance with JQuery as I am new to it and still learning the logic. My goal is to determine which index of a textarea was clicked while holding down the CtrlKey. How can I combine an onclick event with a keyboard event and assign a function? ...

Error: Using `[object HTMLDocument]` as a selector is not recognized in firefox

How can I load my local javascript library and execute an alert command? var jq = document.createElement('script'); jq.src = "http://127.0.0.1/js/jquery-3.3.1.min.js"; document.getElementsByTagName('head')[0].appendChild(jq); $(documen ...