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

Handling errors in Angular and rxjs when encountering undefined returns in find operations

I am currently faced with the challenge of catching an error when the variable selectionId, derived from my route, is null or contains an invalid value. My code structure has a mechanism in place to handle errors when the category variable is undefined, bu ...

Showcase -solely one property object- from numerous property objects enclosed within an array

Hello, I am seeking assistance as I have recently begun learning about angularJS. I am working with objects that have keys such as: scope.eventList=[]; for(){ var event = { id : hash, ...

How can we use the useState hook in React to dynamically generate state variables?

I'm currently working on a React app where input fields need to be stored in the state. While I can use the useState hook to easily store these values, the challenge I'm facing is that I don't know what fields are needed since they are retri ...

What is the best way to craft an if/else statement for a situation when a twig variable is undefined?

When utilizing twig to declare a variable called user: <script type="text/javascript> {% if user is defined %} var user = { example: {{ userjson | raw }} }; {% endif %} </script> If a user is not logged in, an error message a ...

What is the best way to confirm if a Json response is empty or not?

{"PatientPastMedicalHistoryGetResult":{"PastMedicalHistory":[]}} The PastMedicalHistory object does not contain any values. How can I verify if it is empty? ...

Running a Vue.js application on a hosting platform

I am currently facing an issue with my Vue.js application. I have set up a domain and subdomain for the application and now I want to host it. However, when I try to add the subdomain name, I keep encountering 500 Internal server errors. This is my first t ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

New button attribute incorporated in AJAX response automatically

data-original-text is automatically added in ajax success. Here is my code before: <button type="submit" disabled class="btn btn-primary btn-lg btn-block loader" id="idBtn">Verify</button> $(document).on("sub ...

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

The onclick function is malfunctioning when attempting to use the Windows Phone app in Visual Studio 2015

web development <div class="align_center"> <div class="btn EmployeeloginBtn" **onclick="new Employee().connect()**>CONNECT</div> </div> Employee.js: var Employee = function() { var self = this; self.connect = fu ...

What is the current state of Javascript in versions 3.4 and 3.5 of ANTL

Can someone provide information on the current status of the JavaScript target in ANTLR 3.4 or 3.5? I've searched online for answers but haven't found anything conclusive. While I know it was fixed in v3.3 after being broken in v3.2, there is no ...

TinyMCE is substituting the characters "<" with "&lt;" in the text

I am currently using Django with placeholder tags: I am attempting to insert a flash video into my TinyMCE editor, but it is replacing the '<' symbol with < in the code, preventing it from loading properly and only displaying the code. I hav ...

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

JavaScript is a powerful tool for reading JSON files

I'm trying to figure out how to parse a nested object in JSON using JavaScript. Here's the code I have so far: var myRequest = new Request('test.json'); fetch(myRequest) .then(function(response) { return response.json(); }) .then( ...

Bring the element to the top of the page by clicking on the anchor within the element or anywhere within the specified div ID

I am looking to implement a functionality where the page scrolls to the top of the navigation div ID when a link inside the navigation div is clicked, or ideally even when clicking anywhere within the div itself that contains the navigation links. After r ...

Angular: Preserve the URL even when encountering a 404 page

Creating a custom 404 page in Angular 4 is something I have recently done, and I am looking for a way to preserve the incorrect URL that was input by the user. To see an example of this behavior, you can visit sites like GitHub. They show a 404 page when a ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Communicating data transfer between two Node.js servers through the use of the Node Serial Port technology

How can I send the message "Hello world" from one nodejs server to another using node-serialport? I have confirmed that the radios connecting the two servers are properly connected as they are displaying buffer information after running my current code. ...

Fixed-positioned elements

I'm facing a small issue with HTML5 that I can't seem to figure out. Currently, I have a header image followed by a menu div containing a nav element directly below it. My goal is to make the menu div stay fixed when scrolling down while keeping ...