使用jQuery比较两个Javascript对象数组

96
我有两个JavaScript对象数组,我想比较它们是否相同。这些对象在每个数组中的顺序可能不同(大多数情况下会不同)。每个数组不应该超过10个对象。我认为jQuery可能有一个优雅的解决方案来解决这个问题,但我在网上找不到太多信息。
我知道一个嵌套的暴力$.each(array, function(){})解决方案可以工作,但是是否有任何内置函数我不知道吗?
谢谢。
14个回答

0

当我想使用jQuery进行一些数组比较时,我也发现了这个问题。在我的情况下,我有一些字符串,我知道它们是数组:

var needle = 'apple orange';
var haystack = 'kiwi orange banana apple plum';

但我关心它是否完全匹配还是部分匹配,因此我使用了类似于Sudhakar R答案的以下内容:

function compareStrings( needle, haystack ){
  var needleArr = needle.split(" "),
    haystackArr = haystack.split(" "),
    compare = $(haystackArr).not(needleArr).get().length;

  if( compare == 0 ){
    return 'all';
  } else if ( compare == haystackArr.length  ) {
    return 'none';
  } else {
    return 'partial';
  }
}

0
如果重复项很重要,例如[1, 1, 2]不应等于[2, 1]但应等于[1, 2, 1],这里有一个参考计数解决方案:
  const arrayContentsEqual = (arrayA, arrayB) => {
    if (arrayA.length !== arrayB.length) {
      return false}

    const refCount = (function() {
      const refCountMap = {};
      const refCountFn = (elt, count) => {
          refCountMap[elt] = (refCountMap[elt] || 0) + count}
      refCountFn.isZero = () => {
        for (let elt in refCountMap) {
          if (refCountMap[elt] !== 0) {
            return false}}
        return true}
      return refCountFn})()

    arrayB.map(eltB => refCount(eltB, 1));
    arrayA.map(eltA => refCount(eltA, -1));
    return refCount.isZero()}

这里是可以操作的fiddle


0

var arr1 = [
             {name: 'a', Val: 1}, 
             {name: 'b', Val: 2}, 
             {name: 'c', Val: 3}
           ];

var arr2 = [
             {name: 'c', Val: 3},
             {name: 'x', Val: 4}, 
             {name: 'y', Val: 5}, 
             {name: 'z', Val: 6}
           ];
var _isEqual = _.intersectionWith(arr1, arr2, _.isEqual);// common in both array
var _difference1 = _.differenceWith(arr1, arr2, _.isEqual);//difference from array1 
var _difference2 = _.differenceWith(arr2, arr1, _.isEqual);//difference from array2 
console.log(_isEqual);// common in both array
console.log(_difference1);//difference from array1 
console.log(_difference2);//difference from array2 
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>


-3

请尝试这个

function check(c,d){
  var a = c, b = d,flg = 0;
  if(a.length == b.length) 
  { 
     for(var i=0;i<a.length;i++) 
           a[i] != b[i] ? flg++ : 0; 
  } 
  else  
  { 
     flg = 1; 
  } 
  return flg = 0;
}

修改了a和b,只比较第一个元素。真是醉了。 - ScottJ
1
@ScottJ 先生,这个问题是要比较两个数组。如果排序后,两个数组相等,即a[0] == b[0]。你这是什么鬼啊。 - Exception
2
很抱歉,我不知道AH是什么意思,谷歌也没有帮助。但如果我的评论是如此离谱,为什么这段代码在2月21日被完全重写了呢? - ScottJ
@ScottJ 很可能 AH === wtf - Exception

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接