Prevent Repeated Data Input in an Array using JavaScript

I am facing an issue where I need to ensure that the values being inserted are not repeated when performing a push operation.

Below is the snippet of code in question:

addAddress: function() {
            this.insertAddresses.Address = this.address_address;
            this.insertAddresses.State = this.selectedStateAddress;
            this.insertAddresses.City = this.selectedCityAddress;
            if(this.insertAddresses.Address !== "" && this.insertAddresses.State !== null && this.insertAddresses.City !== null) {
                let copy = Object.assign({}, this.insertAddresses);
                this.addresses.push(copy);
            }
            else
            {
                this.$message.error('Not enough data to add');
                return;
            }
        },

Upon adding a new element, the output looks like this:

https://i.stack.imgur.com/qCiiM.png

Subsequently, clicking the add button duplicates the same values. I am seeking guidance on how to implement validation to prevent duplicate entries. What would be the appropriate approach for achieving this?

https://i.stack.imgur.com/6B1rO.png

Answer №1

Before adding an item to the array, make sure it doesn't already exist.

To check if the item is already in the array, you can utilize the Array.prototype.find method:

export default {
  methods: {
    addItem() {
      const newItem = {
        ItemName: this.item_name,
        Quantity: this.selectedQuantity,
        Price: this.item_price
      }
      this.insertNewItem(newItem)
    },
    insertNewItem(item) {
      const existingItem = this.itemsArray.find(i => {
        return 
            i.ItemName === item.ItemName
         && i.Quantity === item.Quantity
         && i.Price === item.Price
      })

      if (!existingItem) {
        this.itemsArray.push(item)
      }
    }
  }
}

If your application requires efficient performance (e.g., dealing with a large number of items), consider maintaining a separate dictionary to keep track of duplicate items:

export default {
  data() {
    return {
      seenItems: {}
    }
  },
  methods: {
    insertNewItem(item) {
      const { ItemName, Quantity, Price } = item
      const key = JSON.stringify({ ItemName, Quantity, Price })
      const seen = this.seenItems[key]

      if (!seen) {
        this.seenItems[key] = item
        this.itemsArray.push(item)
      }
    }
  }
}

example

Answer №2

Take a look at this code snippet:

let filter= this.addresses.find(x=> this.insertAddresses.State==x.State)
if (filter==null) {
   this.$message.error('Error: Address not found');
}

Alternatively, you can filter all the addresses using:

let filter= this.addresses.find(x=> this.insertAddresses.Adress==x.Adress && this.insertAddresses.State==x.State && this.insertAddresses.City==x.City)
if (filter==null) {
   this.$message.error('Error: Address not found');
}
``

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

Remove any list items that do not possess a particular class

My ul list contains several lis, and I need to remove all li elements that do not have children with the class noremove. This is the original HTML: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>I ...

Tips for triggering a JavaScript function within WordPress using an inline function call

While setting up my plugin in the WordPress admin area, I encountered an issue with a form that stores user information. In my file input type, there is a JavaScript function call to my custom JavaScript that I have linked. Here is the line of code causing ...

Truncating long text labels in Material UI Autocomplete using ReactJS

I am currently utilizing the material UI autocomplete feature and I have a specific requirement to trim the label when it is too lengthy. <Autocomplete id="combo-box-demo" options={top100Films} getOptionLabel={(option) =& ...

What is the best way to incorporate new elements into the DOM in order to allow users to share their comments

Can anyone help me with the code below? I have a text box and a comment section, along with a button to add comments. However, I need assistance with adding the posted comment below the comment section. Below is the code snippet: <div id="comments"&g ...

Should a MEAN stack app require the use of two servers in order to run?

Currently, I am in the process of developing a MEAN stack application which involves using MongoDB, ExpressJs, Angular 6, and NodeJs. One issue I am facing is determining whether two servers will be necessary to run the app simultaneously. Specifically, o ...

What is the best way to manage data in a single-page application and retrieve it after the page has been refreshed?

Lately, I’ve encountered an issue with data storage in a single-page application. I’m seeking some guidance on how to effectively store data and retain it after refreshing the page within a Single Page Application. As an example, let's say I hav ...

What could be the reason for the lack of controller updates despite changes made to the service

Could someone please help me solve the issue with my code? I expected that after clicking the button, the text would be updated. However, it seems to not be working as intended. Any assistance you can provide would be greatly appreciated. main.js x = a ...

Could it be that the function is returning undefined because console.log is executing before the result is actually returned? Perhaps a promise

There is a function located in another file that I need to extract the response from and perform an action based on that response before completing my controller function. This is the snippet of code from the external file: exports.counter = function(com ...

The model.find operation is failing to retrieve the necessary fields from the database

When I execute console.log(correct.password), it returns undefined, even though the if condition results in false. app.post('/login' , async (req , res)=> { const correct = data.findOne({name : req.body.name}).select({name : 0}); if(!c ...

Implement a new method called "defer" to an array that will be resolved at a later time using Promise.all()

I need to manage a queue of DB calls that will be executed only once the connection is established. The DB object is created and stored as a member of the module upon connection. DB Module: var db = { localDb: null, connectLocal: (dbName) => { ...

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

AngularJS - $scope.$destroy does not eliminate listeners

I am currently exploring how to develop my own "one-time binding" functionality for AngularJS version 1.2 and earlier. I came across this response which explains the process of creating a custom bindOnce directive. Upon using the provided directive: a ...

What is the best way to exclude an external HTML file from being displayed on the home page?

shopping_cart.php <div id="main-container"> <div class="container"> <span class="top-label"> <span class="label-txt">Shopping Cart</span> </span> <div class="content-area"> <div class="con ...

React event handling

Currently, I am in the process of developing an accordion app using React. The data for this app is fetched from an API, and while I have the basic structure of the app ready, I am facing some difficulties with handling the click event on the accordion. H ...

Getting a Next.js error after performing a hard refresh on a page that contains a dynamic query

I have encountered an issue with my Next.js app when I attempt to hard reload it in production mode. The error message I receive is 404 - File or directory not found. Below is the code snippet I am using: import { useRouter } from "next/router"; import ...

Is it possible for an Ajax/jQuery script to display multiple dependent dropdown box options within a single Form URL?

In the process of developing a basic form prototype that includes 4 entries in PythonAnywhere (Python 3.7 + Django): PinID (Independent, simple manual number entry) Region (Independent Dropdown Box) Name (Region-Dependent Dropdown Box) Source (Name-Depen ...

How to add a service to a static function in Angular

After incorporating a logger service into my project, I have encountered an issue with using it in NGXS static selectors. The selectors in NGXS are static methods, which prevent me from accessing the logger service injected via Angular DI. Are there any e ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Effective sparse translation between whole numbers

I am in the process of developing a specialized regular expression engine that utilizes finite automata. My goal is to manage numerous states, each equipped with its own transition table mapping unicode code points (or UTF-16 code units; I have yet to fina ...

There was an error of "Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor"

I've been diving into cannon.js and encountering the following error: Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor. I've tried numerous solutions but none seem to be working. Here's a snippet of my script: var scene, came ...