Azizi Musa
Azizi Musa

Reputation: 1029

how to prevent duplicate in array push in angularjs

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

Upvotes: 24

Views: 80045

Answers (5)

Chamilyan
Chamilyan

Reputation: 9423

To filter duplicates in an array (es6):

let arr = ['foo', 'foo', 'bar', 'baz'];
Array.from(new Set(arr));
console.log(arr);
// ['foo', 'bar', 'baz'];

Upvotes: 0

gmanolache
gmanolache

Reputation: 497

You should use Angular Filters.

Some implementations can be found as answers to a similar question: How to make ng-repeat filter out duplicate results

Upvotes: 1

ryeballar
ryeballar

Reputation: 30098

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>

Upvotes: 2

Vamsi
Vamsi

Reputation: 9780

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
}

Upvotes: 9

xxmicloxx
xxmicloxx

Reputation: 613

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.

Upvotes: 43

Related Questions