Reputation: 1145
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.
Upvotes: 1
Views: 8934
Reputation: 198
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;
Upvotes: 1
Reputation: 11613
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)
Upvotes: 1
Reputation: 5962
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
Upvotes: 1