是否有一种方法可以在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"]
当前回答
为了获得对称差异,您需要以两种方式比较数组(或在多个数组的情况下以所有方式比较)
ES7 (ECMAScript 2016)
// diff between just two arrays:
function arrayDiff(a, b) {
return [
...a.filter(x => !b.includes(x)),
...b.filter(x => !a.includes(x))
];
}
// diff between multiple arrays:
function arrayDiff(...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter(x => !unique.includes(x));
}));
}
ES6(2015年ECMAScript)
// diff between just two arrays:
function arrayDiff(a, b) {
return [
...a.filter(x => b.indexOf(x) === -1),
...b.filter(x => a.indexOf(x) === -1)
];
}
// diff between multiple arrays:
function arrayDiff(...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter(x => unique.indexOf(x) === -1);
}));
}
ES5 (ECMAScript 5.1)
// diff between just two arrays:
function arrayDiff(a, b) {
var arrays = Array.prototype.slice.call(arguments);
var diff = [];
arrays.forEach(function(arr, i) {
var other = i === 1 ? a : b;
arr.forEach(function(x) {
if (other.indexOf(x) === -1) {
diff.push(x);
}
});
})
return diff;
}
// diff between multiple arrays:
function arrayDiff() {
var arrays = Array.prototype.slice.call(arguments);
var diff = [];
arrays.forEach(function(arr, i) {
var others = arrays.slice(0);
others.splice(i, 1);
var otherValues = Array.prototype.concat.apply([], others);
var unique = otherValues.filter(function (x, j) {
return otherValues.indexOf(x) === j;
});
diff = diff.concat(arr.filter(x => unique.indexOf(x) === -1));
});
return diff;
}
例子:
// diff between two arrays:
const a = ['a', 'd', 'e'];
const b = ['a', 'b', 'c', 'd'];
arrayDiff(a, b); // (3) ["e", "b", "c"]
// diff between multiple arrays
const a = ['b', 'c', 'd', 'e', 'g'];
const b = ['a', 'b'];
const c = ['a', 'e', 'f'];
arrayDiff(a, b, c); // (4) ["c", "d", "g", "f"]
对象数组之间的差异
function arrayDiffByKey(key, ...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter( x =>
!unique.some(y => x[key] === y[key])
);
}));
}
例子:
const a = [{k:1}, {k:2}, {k:3}];
const b = [{k:1}, {k:4}, {k:5}, {k:6}];
const c = [{k:3}, {k:5}, {k:7}];
arrayDiffByKey('k', a, b, c); // (4) [{k:2}, {k:4}, {k:6}, {k:7}]
其他回答
根据之前的答案…取决于你是想要一个高效的还是“漂亮的联机”解决方案。
一般有三种方法……
"manual iterative" (using indexOf) - naive with O(n2) complexity (slow) var array_diff_naive = function(a,b){ var i, la = a.length, lb = b.length, res = []; if (!la) return b; else if (!lb) return a; for (i = 0; i < la; i++) { if (b.indexOf(a[i]) === -1) res.push(a[i]); } for (i = 0; i < lb; i++) { if (a.indexOf(b[i]) === -1) res.push(b[i]); } return res; } "abstract iterative" (using filter and concat library methods) - syntactic sugar for manual iterative (looks nicer, still sucks) var array_diff_modern = function(a1,a2){ return a1.filter(function(v) { return !a2.includes(v); } ) .concat(a2.filter(function(v) { return !a1.includes(v);})); } "using hashtable" (using object keys) - much more efficient - only O(n), but has slightly limited range of input array values var array_diff_hash = function(a1,a2){ var a = [], diff = []; for (var i = 0; i < a1.length; i++) { a[a1[i]] = true; } for (var i = 0; i < a2.length; i++) { if (a[a2[i]]) { delete a[a2[i]]; } else { a[a2[i]] = true; } } for (var k in a) { diff.push(k); } return diff; }
在jsperf上可以看到 https://jsperf.com/array-diff-algo
如果你的数组包含对象,如果你想比较一个属性,就会变得有点困难。
幸运的是,lodash使用_contains和_.pluck使这非常简单:
var list1 = [{id: 1},{id: 2}];
var list1 = [{id: 1},{id: 2}, {id: 3}];
//es6
var results = list2.filter(item => {
return !_.contains(_.pluck(list1, 'id'), item.id);
});
//es5
var results = list2.filter(function(item){
return !_.contains(_.pluck(list1, 'id'), item.id);
});
//results contains [{id: 3}]
Array.prototype.diff =函数(a) { return this.filter(function(i) {return a.f index_of (i) < 0;}); }; ////////////// //示例// ////////////// Const dif1 =[1,2,3,4,5,6]。Diff ([3,4,5]); console.log (dif1);// => [1,2,6] const dif2 =[“test1”、“test2”,“test3”,“test4”,“test5”,“test6”].diff([“test1”、“test2”,“test3”、“test4”)); console.log (dif2);// => ["test5", "test6"]
注意:. indexof()和.filter()在IE9之前是不可用的。
我就遇到了这个问题,就是求两个简单数组的差值
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
我不明白为什么不使用基本的for循环:
for(var i=0; i < a1.length; i++) {
for(var j=0; j < a2.length; j++) {
if(a1[i] == a2[j]) {
a2.splice(j, 1);
}
}
}
这将返回所需的["c", "d"]
[编辑]提议正上方,看到晚了。
不管怎样,有什么好的理由来避免这个简单的解决方案吗?
const a1 = ['a', 'b', 'c', 'd'];
const a2 = ['a', 'b'];
const diffArr = a1.filter(o => !a2.includes(o));
console.log(diffArr);
输出:
[ 'a', 'b' ]