从 JavaScript 中的 2 个数组中获取不匹配的值

Getting unmatched values from 2 arrays in JavaScript?

本文关键字:获取 不匹配 数组 JavaScript 中的      更新时间:2023-09-26

假设我们有 2 个数组说:

 A [] => 1 2 3 4 5
 B [] => 1 2 7 4 5 

在这种情况下,jQuery 中是否有任何方法可以给出 2 个数组的不匹配值:

 Result [] => 3 7

hiya 在这里工作演示:http://jsfiddle.net/mbKfT/

好读 http://api.jquery.com/jQuery.inArray/

这使用inArray来检查它是否存在元素,如果不将其添加到数组intersect

REST 演示将提出任何疑问:)

法典

var a1 = [1,2,3,4,5];
var a2 = [1,2,7,4,5];
var intersect = [];
$.each(a1, function(i, a1val) {
    if ($.inArray(a1val, a2) === -1) {   
        intersect.push(a1val);
    }
});
$.each(a2, function(i, a1val) {
    if ($.inArray(a1val, a1) === -1) {           
        intersect.push(a1val);
    }
});
$("div").text(intersect);
alert(intersect + " -- " + matches);
​

答案:否。

解决方案:使用标准的JavaScript循环。

var nomatches = [];
for (var i=Math.min(A.length, B.length); i-->0;) {
   if (A[i]!=B[i]) {
       nomatches.push(A[i]);
       nomatches.push(B[i]);
   }
}
// do what you want with remaining items if A.length != B.length

如果,正如 Rory 所假设的那样,您不想匹配数组而是逻辑集,您可以这样做:

 var nomatches = [];
var setA = {};
var setB = {};
for (var i=A.length; i-->0;) setA[A[i]]=1;
for (var i=B.length; i-->0;) setB[B[i]]=1;
for (var i=A.length; i-->0;) {
    if (!setB[A[i]]) nomatches.push(A[i]);
}
for (var i=B.length; i-->0;) {
    if (!setA[V[i]]) nomatches.push(B[i]);
}
var nomatch = [], Bcopy = B.slice(0);
for (var i = 0, j; i < A.length; i++) {
    j = Bcopy.indexOf(A[i]);
    if (j === -1) nomatch.push(A[i]);
    else Bcopy.splice(j, 1);
}
nomatch.push.apply(nomatch, Bcopy);

注意:

  1. 此代码假定 AB 中的项是唯一的。
  2. 数组的indexOf必须在 IE8 和早期版本中模拟。

jQuery.inArray() 会做一些帮助:

var a = [1,2,3,4,5], b=[1,2,7,4,5];
var ret = 
a.filter(function(el) {
  return $.inArray(el, b) === -1;
}).concat(
b.filter(function(el) {
  return $.inArray(el, a) === -1;    
})
);
console.log(ret);

演示。

PS:或者你可以只使用b.indexOf(el) === -1,那么你就不再需要jQuery了。

function getUnique(A, B){
  var res = [];
  $.grep(A, function(element) {
    if($.inArray(element, B) == -1) res.push(element)        
  });
  $.grep(B, function(element) {
    if($.inArray(element, A) == -1) res.push(element);    
  });
  return res;
}

用:

var A = [1,2,3,4,5],
    B = [1,2,3,5,7];
getUnique(A, B);

演示

这是现代浏览器的另一种解决方案(单行,是的!

var a = [1, 2, 3, 4, 5];
var b = [1, 2, 7, 4, 5];
var result = a.concat(b).filter(function(el, i) {
    return (i < a.length ? b : a).indexOf(el) == -1;
});

演示:http://jsfiddle.net/6Na36/


如果您还希望保留索引检查,则可以使用此变体:

var a = [1, 2, 3, 4, 5];
var b = [1, 2, 7, 4, 5];
var result = a.concat(b).filter(function(el, i, c) {
    return el != c[i < a.length ? i + a.length : i - a.length];
});

演示:http://jsfiddle.net/6Na36/1/

请注意,这两种变体都成功地处理了不同大小的数组。