I push the data into an array. Before pushing, I check name already exists or not.
I checked whether the same name available in the array or not
If it exists alert throws " duplicate items"
If it is a new item, it will push into an array.
The below code has been working fine till now
But when I edit the existing item address field, it will throw the duplicate alert items
this.arrayData = [{
"name": "sachin",
"address": "india"
}, {
"name": "bin",
"address": "us"
}, {
"name": "gill",
"address": "aus"
}]
var isInArray = this.arrayData.filter(c=>c.name === this.data.name);
if (isInArray.length > 0) {
alert("dublicate items");
} else {
this.saveItems(this.data);
}
If you dont want duplicates on array, just use Set, example code:
let abc = ['a', 'b', 'c', 'd']
function saveItems(newItem) {
abc = [...abc, newItem]
abc = [...new Set(abc)]
}
saveItems('d')
saveItems('d')
saveItems('e')
console.log(abc)
//output: (5) ["a", "b", "c", "d", "e"]
I tried below solution to achieve the result.
for(var i=0;i < this.arrayData.length;i++)
{
if(i=== index)
{
if(this.arrayData[i].Name === this._data.Name )
{
this.saveItems(this.data); break;
}
else if(this.arrayData[i].Name !== this._data.Name )
{
var dataCheck = this.editDublicate(index);
if(!dataCheck) {
this.saveItems(this.data); break;
}
}
}
}
editDublicate(index)
{
var dublicateData =false;
for(var i=0;i < this.arrayData.length;i++)
{
if(this.arrayData[i].Name === this._data.Name && i !== index)
{
alert("dublicate items");
break;
}
}
return dublicateData;
}