Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array is unique on specific object property?

I have an array of objects:

var array1 = [
  {
    property1: 10,
    property2: "abc"
  }, 
  {
    property1: 11,
    property2: "def"
  },
  {
    property1: 10,
    property2: "ghi"
  }
];

Now what I want is this array will be said not unique as per value of property1.

This means that this array contains 2 elements with property1=10, so the array does not contain unique value of property1.

To check this, I can use a for loop:

for (var i = 0; i < array1.length; i++) {
  var array2 = array1.slice(); // copy array
  array2.remove(array1[i]);
  var temppropety1 = array1[i].property1;
  for (var j = 0; j < array2.length; j++) {
    if (array2[J].property1==temppropety1) {
      return true;
    }
  }
}

But is there an easier way or a library to find this?

like image 968
kakon Avatar asked May 28 '15 07:05

kakon


2 Answers

Here is a straightforward way to test for uniqueness on property1. Loop through the objects in the outer array and add each object's property1 to a temp array if it is not already in that temp array. If a duplicate value is encountered, return false meaning property1 is not unique.

function isUnique(arr) {
   var tmpArr = [];
   for(var obj in arr) {
     if(tmpArr.indexOf(arr[obj].property1) < 0){ 
       tmpArr.push(arr[obj].property1);
     } else {
       return false; // Duplicate value for property1 found
     }
   }
   return true; // No duplicate values found for property1
}

Demo: http://jsbin.com/lohiqihipe/1/

like image 198
Drakes Avatar answered Nov 09 '22 19:11

Drakes


I suggest that array can be quite big so I'd prefer not to copy it and just validate properties.

Also it is not an option to use map function of array because in this case you won't be able to break a cycle on first match:

var equals = function(array) {
    var co = {};
    var unique = true;
    for(var i = 0; i < array.length; i++) {
        var o = array[i];
        if (co[o.property1]) {
            unique = false;
            break;
        } else {
            co[o.property1] = true;
        }
    }
    return unique;
};
like image 37
nesteant Avatar answered Nov 09 '22 19:11

nesteant