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

1
  • You can use jQuery's grep. See this Commented Sep 15, 2015 at 12:34

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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
}

2 Comments

i tried to use this, but not working. And i still want update the number in array, just not push the whole element to end of array
check the modified example
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>

Comments

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

Comments

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'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.