how to prevent duplicate in array push in angularjs how to prevent duplicate in array push in angularjs angularjs angularjs

how to prevent duplicate in array push in angularjs


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.


Just javascript is enough.

If an array contains the item its index is >= 0

so you can do this, if index == -1 , item does not exist in the array, so you can push unique item

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

Edit: You asked for changing the number, this is how

var index = arr.indexOf(item);if(index > -1) { //checking if item exist in array  arr[index]++;   // you can access that element by using arr[index],                  // then change it as you want, I'm just incrementing in above example}


As what most of the answers have pointed out, you can use the Array.prototype.indexOf() method to determine if a value exists or not. In order to check for this, check the array of strings against your ng-models value property, selects.value, within the ng-change() event callback.

DEMO

Javascript

$scope.goChange = function(name, value){  if(!~arr.indexOf(value)) {          arr.push(name, value);          console.log(arr);  }};

HTML

<select ng-model="selects" ng-change="goChange(item.name, selects.value)" ng-options="i as i.value for i in options">  <option value=""></option></select>