Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent duplicate in array push in angularjs

Tags:

my code is like this :

var arr = []; arr.push(item1,item2); 

so arr will contain like: ["name","thing1"]

But i got problem when pushing element with same exact value, how do i filter same element value but still accepting update/changes. JSFIDDLE

like image 833
Azizi Musa Avatar asked Sep 04 '14 13:09

Azizi Musa


People also ask

How to prevent Duplicate in array push in angular?

You can use arr. indexOf which returns -1 if it is not found, so you can add it then.

How to prevent Duplicates in an array js?

To prevent adding duplicates to an array:Use the Array. includes() method to check if the value is not present in the array. If the value is not present, add it to the array using the push() method. The array will not contain any duplicate values.

How do you prevent duplicates in NG repeat?

You can use unique filter while using ng-repeat . If you use track by $index then unique won't work.


1 Answers

You can use arr.indexOf which returns -1 if it is not found, so you can add it then.

e.g.

if (arr.indexOf(item) == -1) {     arr.push(item); } 

However, this does not work in old browsers...

JQuery has a method ($.indexOf) that works in every browser, even very old ones.

like image 148
xxmicloxx Avatar answered Dec 26 '22 13:12

xxmicloxx