是否有一种方法可以在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"]
当前回答
const difference = function (baseArray, arrayToCampare, callback = (a, b) => a!== b) {
if (!(arrayToCampare instanceof Array)) {
return baseArray;
}
return baseArray.filter(baseEl =>
arrayToCampare.every(compareEl => callback(baseEl, compareEl)));
}
其他回答
function array_diff(a, b) {
let array = [];
for(let i = 0; i <a.length; i++) {
let k = 0;
for( let j = 0; j < b.length; j++) {
if(a[i]!==b[j]) {
k++;
}
if(k===b.length) {
array = array.concat(a[i]);
}
}
if(b.length ===0) {
array = array.concat(a[i]);
}
}
return array;
}
使用http://phrogz.net/JS/ArraySetMath.js你可以:
var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];
var array3 = array2.subtract( array1 );
// ["test5", "test6"]
var array4 = array1.exclusion( array2 );
// ["test5", "test6"]
如果不使用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;
}
这个问题很老了,但仍然是javascript数组减法的热门问题,所以我想添加我正在使用的解决方案。适用于以下情况:
var a1 = [1,2,2,3]
var a2 = [1,2]
//result = [2,3]
下面的方法将产生预期的结果:
function arrayDifference(minuend, subtrahend) {
for (var i = 0; i < minuend.length; i++) {
var j = subtrahend.indexOf(minuend[i])
if (j != -1) {
minuend.splice(i, 1);
subtrahend.splice(j, 1);
}
}
return minuend;
}
需要注意的是,该函数不包括减数中没有被减数的值:
var a1 = [1,2,3]
var a2 = [2,3,4]
//result = [1]
function diffArray(arr1, arr2) {
var newArr = arr1.concat(arr2);
return newArr.filter(function(i){
return newArr.indexOf(i) == newArr.lastIndexOf(i);
});
}
这对我很有用