简体   繁体   中英

Loop array of objects, compare key values

I have an array of objects, all with the same keys. I want to check if 2 keys, in this case "a" & "b" from ALL OBJECTS, have the same value. Meaning a === a and b === b, across all objects.

var arr = [{a:"x", b:2, c:3, d:4},{a:1, b:2, c:3, d:4},{a:1, b:2, c:3, d:4},{a:1, b:2, c:3, d:4}];

if one of the key values(a or b) doesn't match the others, I want to return false. This case should return false because "a" in arr[0] = "x", while all the others equal 1;

Here's my attempt. Obviously doesnt work but what I was attempting was to have 2 loops compare 2 objects at a time. For example, the first loop will start at arr[0] and second loop will start at arr[1], compare then move onto comparing arr[3] with arr[4] and so on. Though the length of the array wont always be even.

function compareKeyVals(arr){

  for(var i = 0; i<arr.length; i+=2){
    for(var j = 1; j<arr.length; j+=2){
     for(key in arr[i]){     
        for(keyz in arr[j]){      
          if(key === "a" && keyz === "a"){
            if(arr[i][key] != arr[j][keyz]){
              return false;
            }
          }  
        }
      }    
    }
  }
}

compareKeyVals(arr);

thanks.

Since they all have to be equal, you can just check the a and b properties of the first object and compare all others against that. Like so:

for(var i=1; i<arr.length; i++){
  if(arr[i].a !== arr[0].a || arr[i].b !== arr[0].b) {
    return false;
  }
}
return true;

Update: Changed to strict comparison, inspired by Marc's answer

var flag = true;  
for(var i = 1; i<arr.length; i++){
if(arr[0].a != arr[i].a || arr[0].b != arr[i].b){
flag = false;
break;
 }
}
return flag;

You can really just detect a change from one iteration to the next, right?

 var arrayLength = arr.length; //cache the array length
 if (arrayLength > 0) { //only proceed if there are some elements
   var firstA = arr[0].a; //set the baseline that all others must match
   var firstB = arr[0].b;
   for(var i = 1; i<arrayLength ; i++) {
       //if the new one doesn't match the first one, break out
       if (firstA !== arr[i].a || firstB !== arr[i].b) {
           return false;
       }
   }
   return true; //return true if we complete the loop with all matches
 } else {
   return false; //assumes you want to return false if no elements in array
 }

This will break you out of the loop immediately when it finds a mismatch, so you're not wasting iterations.

(added a check for empty array per comment)

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