0

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);
            }
hussain
  • 6,587
  • 18
  • 79
  • 152

3 Answers3

1

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.

Comptonburger
  • 583
  • 3
  • 10
1

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);
}
isvforall
  • 8,768
  • 6
  • 35
  • 50
0

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);
               }
}
KpTheConstructor
  • 3,153
  • 1
  • 14
  • 22