Skip to content Skip to sidebar Skip to footer

Compare Two Arrays Javascript - Associative

I have searched on here for a quality method to compare associative arrays in javascript. The only decent solution I have found is the PHP.JS project which has some comparative arr

Solution 1:

This is an old question, but since it comes up first in a google search for comparing arrays, I thought I would throw in an alternative solution that works even when the array has two different objects with the same values.

functionarrays_equal(a, b) {
    returnJSON.stringify(a) == JSON.stringify(b);
}

Note: This is order dependent, so if order doesn't matter, you can always do a sort ahead of time.

Solution 2:

I think the following should do what you want:

function nrKeys(a) {
    var i = 0;
    for (key in a) {
        i++;
    }
    return i;
}
function compareAssociativeArrays(a, b) {
   if (a == b) {
       returntrue;
   }   
   if (nrKeys(a) != nrKeys(b)) {
       returnfalse;
   }
   for (key in a) {     
     if (a[key] != b[key]) {
         returnfalse;
     }
   }
   returntrue;
}

Solution 3:

I really don't know if there is a nicer way to do it than the brute force approach:

functiondifferences(a, b){
  var dif = {};
  for(key in a){ //In a and not in bif(!b[key]){
      dif[key] = a[key];
    }
  }
  for(key in a){ //in a and b but different valuesif(a[key] && b[key] && a[key]!=b[key]){
      //I don't know what you want in this case...
    }
  }
  for(key in b){ //in b and not in aif(!a[key]){
      dif[key] = b[key];
    }
  }
  return dif;
}

Also, they are objects, not arrays, and some properties will not be enumerable through for..in (like Array.length, for example), so take it into account for your application.

Post a Comment for "Compare Two Arrays Javascript - Associative"