Skip to content Skip to sidebar Skip to footer

Compare Objects In An Array

I have an array of objects. var array = [obj1, obj2, obj3, objN] every objects has 3 properties key, name, description. How can i compare these objects for equality, two objects a

Solution 1:

You can do that using Array.prototype.every():

The every() method tests whether all elements in the array pass the test implemented by the provided function. (mdn)

Example:

vararray = [obj1, obj2, obj3, objN];
var allTheSame = array.every(function(element){
    return element.key === array[0].key;
});

Please note that Array.prototype.every() is IE 9+. However, there's a nice polyfill on the mdn page for older versions of IE.

If you really want to use a for loop, you could do it like this:

vararray = [obj1, obj2, obj3, objN];
var allTheSame = array.length == 1;

for(var i = 1; i < array.length && (array.length > 1 && allTheSame); i++){
    allTheSame = array[0].key == array[i].key;
}

Try it for:

[{key:1},{key:1},{key:1}]; // true[{key:1},{key:1},{key:2}]; // false[{key:1},{key:2},{key:1}]; // false[{key:1}]; // true

Solution 2:

vararray = [obj1, obj2, obj3, objN];
for(i = 0, i < array.length; i++){
    for(j = i + 1; j < array.length; j++){
        if(array[i].key == array[j].key){
            // Your logic whatever you want to do here.
        }
    }
}

Post a Comment for "Compare Objects In An Array"