是否有一种方法可以在JavaScript中返回两个数组之间的差异?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
是否有一种方法可以在JavaScript中返回两个数组之间的差异?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
当前回答
如果不使用hasOwnProperty,那么我们有不正确的元素。例如:
[1,2,3].diff([1,2]); //Return ["3", "remove", "diff"] This is the wrong version
我的版本:
Array.prototype.diff = function(array2)
{
var a = [],
diff = [],
array1 = this || [];
for (var i = 0; i < array1.length; i++) {
a[array1[i]] = true;
}
for (var i = 0; i < array2.length; i++) {
if (a[array2[i]]) {
delete a[array2[i]];
} else {
a[array2[i]] = true;
}
}
for (var k in a) {
if (!a.hasOwnProperty(k)){
continue;
}
diff.push(k);
}
return diff;
}
其他回答
试一试。
var first = [ 1, 2, 3, 4, 5 ];
var second = [ 4, 5, 6 ];
var difference = first.filter(x => second.indexOf(x) === -1);
console.log(difference);
Output: [ 1, 2, 3]
Var first = [1,2,3,4,5]; Var second = [4,5,6]; Var差=第一。filter(x => second.indexOf(x) === -1); console.log(差异);
修正了一下最佳答案
function arr_diff(a1, a2)
{
var a=[], diff=[];
for(var i=0;i<a1.length;i++)
a[a1[i]]=a1[i];
for(var i=0;i<a2.length;i++)
if(a[a2[i]]) delete a[a2[i]];
else a[a2[i]]=a2[i];
for(var k in a)
diff.push(a[k]);
return diff;
}
这将考虑当前的元素类型。B /c当我们创建一个[a1[i]]时,它将一个值从原始值转换为字符串,因此我们失去了实际值。
随着ES6的到来,带有sets和splat操作符(当时只在Firefox中工作,请检查兼容性表),你可以编写以下一行代码:
var a = ['a', 'b', 'c', 'd'];
var b = ['a', 'b'];
var b1 = new Set(b);
var difference = [...new Set(a.filter(x => !b1.has(x)))];
结果是["c", "d"]。
CoffeeScript版本:
diff = (val for val in array1 when val not in array2)
只是想…为了一个挑战;-)这个工作…(对于字符串,数字等的基本数组)没有嵌套数组
function diffArrays(arr1, arr2, returnUnion){
var ret = [];
var test = {};
var bigArray, smallArray, key;
if(arr1.length >= arr2.length){
bigArray = arr1;
smallArray = arr2;
} else {
bigArray = arr2;
smallArray = arr1;
}
for(var i=0;i<bigArray.length;i++){
key = bigArray[i];
test[key] = true;
}
if(!returnUnion){
//diffing
for(var i=0;i<smallArray.length;i++){
key = smallArray[i];
if(!test[key]){
test[key] = null;
}
}
} else {
//union
for(var i=0;i<smallArray.length;i++){
key = smallArray[i];
if(!test[key]){
test[key] = true;
}
}
}
for(var i in test){
ret.push(i);
}
return ret;
}
array1 = "test1", "test2","test3", "test4", "test7"
array2 = "test1", "test2","test3","test4", "test5", "test6"
diffArray = diffArrays(array1, array2);
//returns ["test5","test6","test7"]
diffArray = diffArrays(array1, array2, true);
//returns ["test1", "test2","test3","test4", "test5", "test6","test7"]
注意排序可能不会像上面提到的那样…但是如果需要的话,可以在数组上调用.sort()对其进行排序。