24

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

Azizi Musa
  • 1,009
  • 2
  • 10
  • 31

5 Answers5

43

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.

xxmicloxx
  • 613
  • 6
  • 15
9

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
}
Vamsi
  • 9,510
  • 6
  • 38
  • 46
2

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>
ryeballar
  • 29,658
  • 10
  • 65
  • 74
1

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

Community
  • 1
  • 1
gmanolache
  • 497
  • 4
  • 12
0

To filter duplicates in an array (es6):

let arr = ['foo', 'foo', 'bar', 'baz'];
Array.from(new Set(arr));
console.log(arr);
// ['foo', 'bar', 'baz'];
Chamilyan
  • 9,347
  • 10
  • 38
  • 67