How to stop duplicates when pushing data to a multidimensional array in Vue js?

First, you will have to search for the index position of the element you are looking for. In this example, I will search for the ID:

This is how I will push the data to my array:

this.myArray.push({
id: data.id,
first_name: data.first_name,
last_name: data.last_name
});

To search for the index use this code:

let index = this.myArray.findIndex(function(value) {
return value.id === data.id;
});

In my above example, the “data.id”, comes from the ID I do not want duplicated in my array.

It could come from a button click or a loop.

Due to the fact that we have 2 elements in our above array as “id”, “first_name” and “last_name”, we can search now for:

value.id
value.first_name
value.last_name

To delete the element, simply use the index element position(by first looking for it with the above code

 this.myArray.splice(index, 1);

To stop duplicated insertions:

if(index === -1) {
    this.myArray.push({
        id: data.id,
        first_name: data.first_name,
        last_name: data.last_name
    });
}

In the case when looking for the index position, “-1” means not found. They could not use 0,1,2,3,4 as those will be used for the index position of the element you are looking for (it makes sense!).

Enjoy and please leave us a comment if you like this piece of code!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Disclaimer:

As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.