简体   繁体   中英

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 are equal if they have the same key.

But if a have lets say 4 objects they all must have the same key to be equal.

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:

var array = [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:

var array = [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
var array = [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.
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM