使用javascript检查两个数组之间的差异

时间:2017-06-22 13:19:07

标签: javascript

我有两个数组,所以我想显示缺少的array1值或者与array2相比的额外值。

例如:

var array1 = [1,1,2,3,5,6]; var array2 = [0,1,2,4];

结果: ==>缺少:0,1,4 ==>额外:3,5,6

2 个答案:

答案 0 :(得分:0)

对于一个非常愚蠢的实现,你可以自己检查一下:

var array1 = [1, 2, 3, 5, 6];
var array2 = [0, 1, 2, 4];

var missing = [];
var extra = [];
for(var i = 0; i < Math.max(array1.length, array2.length); i++) {
    if (i < array1.length && array2.indexOf(array1[i]) === -1) {
        extra.push(array1[i]);
    }
    if (i < array2.length && array1.indexOf(array2[i]) === -1) {
        missing.push(array2[i]);
    }
}

console.log('Result: ==> Missing: ' + missing + ' Extra: ' + extra);

或者,如果您可以使用filter

var array1 = [1, 2, 3, 5, 6];
var array2 = [0, 1, 2, 4];

var extra = array1.filter(function(item) { return array2.indexOf(item) === -1 });
var missing = array2.filter(function(item) { return array1.indexOf(item) === -1 });

console.log('Result: ==> Missing: ' + missing + ' Extra: ' + extra);

答案 1 :(得分:0)

&#13;
&#13;
function comparator(a, b) { return a - b }

function compare(ar1, ar2) {
  ar1 = ar1.slice().sort(comparator)
  ar2 = ar2.slice().sort(comparator)
  let missing = []
  let extra = []
  let pos1 = 0
  let pos2 = 0
  while(pos1 < ar1.length && pos2 < ar2.length) {
    const item1 = ar1[pos1]
    const item2 = ar2[pos2]
    if (item1 === item2) {
      pos1++
      pos2++
    } else if (item1 < item2) {
      extra.push(item1)
      pos1++
    } else {
      missing.push(item2)
      pos2++
    }
  }
  extra = extra.concat(ar1.slice(pos1))
  missing = missing.concat(ar2.slice(pos2))
  return {
  missing,
  extra
  }
}

console.log(compare([1,1,2,3,5,6], [0,1,2,4]))
&#13;
&#13;
&#13;