Validate Duplicate Data Entry in Array - JavaScript

Viewed 1028

My problem is that I want to insert values that are not repeated when doing a push

This is my code :

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

When adding a new element to my object, it returns the following.

enter image description here

When I press the add button again, it adds the same values again, I want to perform a validation so that the data is not the same. How could I perform this validation in the correct way?

enter image description here

2 Answers

check it:

let filter= this.addresses.find(x=> this.insertAddresses.State==x.State)
if (filter==null) {
   this.$message.error('your message');
}

OR FILTER ALL

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('your message');
}
``

Verify that the item doesn't already exist in the array before inserting.

You can search the array using Array.prototype.find:

export default {
  methods: {
    addAddress() {
      const newItem = {
        Address: this.address_address,
        State: this.selectedStateAddress,
        City: this.selectedCityAddress
      }
      this.insertItem(newItem)
    },
    insertItem(item) {
      const existingItem = this.addresses.find(a => {
        return 
            a.State === item.State
         && a.City === item.City
         && a.Address === item.Address
      })

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

On the other hand, if your app requires better performance (e.g., there are many addresses), you could save a separate dictonary to track whether the address already exists:

export default {
  data() {
    return {
      seenAddresses: {}
    }
  },
  methods: {
    insertItem(item) {
      const { Address, State, City } = item
      const key = JSON.stringify({ Address, State, City })
      const seen = this.seenAddresses[key]

      if (!seen) {
        this.seenAddresses[key] = item
        this.addresses.push(item)
      }
    }
  }
}

demo

Related