Compare two Arrays Javascript - Associative

此生再无相见时 提交于 2019-12-01 16:57:43

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.

function arrays_equal(a, b) {
    return JSON.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.

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) {
       return true;
   }   
   if (nrKeys(a) != nrKeys(b)) {
       return false;
   }
   for (key in a) {     
     if (a[key] != b[key]) {
         return false;
     }
   }
   return true;
}

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

function differences(a, b){
  var dif = {};
  for(key in a){ //In a and not in b
    if(!b[key]){
      dif[key] = a[key];
    }
  }
  for(key in a){ //in a and b but different values
    if(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 a
    if(!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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!