hussain
hussain

Reputation: 7123

How to check if value existed in array or not?

I dont want to push duplicate values into selectedOwners, so in below code user is selecting owner if owner already existed in selectedOwners array i dont want to push , How can i check that to avoid duplicate values in an array ?

ctrl.js

  var selectedOwners = [];
            $scope.addProcessOwner = function(dataItem){
              var selectedOwner = {
                  fullName: dataItem.fullName,
                  workerKey: dataItem.workerKey
              }
              if(selectedOwners.indexOf(selectedOwner) !== -1) {
                selectedOwners.push(selectedOwner);
               }
              console.log('WORKER DATA',selectedOwners);
            }

Upvotes: 0

Views: 60

Answers (3)

isvforall
isvforall

Reputation: 8926

You can use Array.prototype.some method

The some() method tests whether some element in the array passes the test implemented by the provided function.

var isExists = function(e) {
    if (e.fullName == selectedOwner.fullName
        && e.workerKey == selectedOwner.workerKey) {
        return true;
    }
}

if (!selectedOwners.some(isExists)) {
    selectedOwners.push(selectedOwner);
}

Upvotes: 1

KpTheConstructor
KpTheConstructor

Reputation: 3291

Try wrapping your "if" logic in a for-loop .

Example

//Following code loops through array and check for already existing value

for(var i = 0; i < selectedOwners.length; i++){
if(selectedOwners.indexOf(selectedOwner) !== -1) {
                selectedOwners.push(selectedOwner);
               }
}

Upvotes: 0

Comptonburger
Comptonburger

Reputation: 594

The use of Array.indexOf is obvious for simple types like strings and numbers.

However, when you are looking for an object, you have to pass the exact same object. A different object with all the same properties and values will still not work. Think of the array as containing pointers to the objects and you must look for the same pointer.

Instead you will need to write your own method to compare the owners for equality and loop through the array doing this check.

Upvotes: 1

Related Questions