是否有一种方法可以在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"]
当前回答
下划线中的差分方法(或它的替换,Lo-Dash)也可以做到这一点:
(R)eturns the values from array that are not present in the other arrays
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
与任何下划线函数一样,你也可以以更面向对象的风格使用它:
_([1, 2, 3, 4, 5]).difference([5, 2, 10]);
其他回答
下面是另一个可以返回差异的解决方案,就像git diff一样:(它已经用typescript编写,如果你不使用typescript版本,只需删除类型)
/**
* util function to calculate the difference between two arrays (pay attention to 'from' and 'to'),
* it would return the mutations from 'from' to 'to'
* @param { T[] } from
* @param { T[] } to
* @returns { { [x in string]: boolean } } it would return the stringified version of array element, true means added,
* false means removed
*/
export function arrDiff<T>(from: T[], to: T[]): { [x in string]: boolean } {
var diff: { [x in string]: boolean } = {};
var newItems: T[] = []
diff = from.reduce((a, e) => ({ ...a, [JSON.stringify(e)]: true }), {})
for (var i = 0; i < to.length; i++) {
if (diff[JSON.stringify(to[i])]) {
delete diff[JSON.stringify(to[i])]
} else {
newItems.push(to[i])
}
}
return {
...Object.keys(diff).reduce((a, e) => ({ ...a, [e]: false }), {}),
...newItems.reduce((a, e) => ({ ...a, [JSON.stringify(e)]: true }), {})
}
}
下面是一个用法示例:
arrDiff(['a', 'b', 'c'], ['a', 'd', 'c', 'f']) //{"b": false, "d": true, "f": true}
这个答案是2009年写的,所以有点过时了,但是对于理解这个问题还是很有教育意义的。我今天最好的解决办法是
let difference = arr1.filter(x => !arr2.includes(x));
(此处致谢给其他作者)
我假设你比较的是一个普通数组。如果不是,你需要将for循环改为for ..在循环。
函数arr_diff (a1, a2) { Var a = [], diff = []; For (var I = 0;I < a1.length;我+ +){ A [a1[i]] = true; } For (var I = 0;I < a2.length;我+ +){ If (a[a2[i]]) { 删除一个[a2[我]]; }其他{ A [a2[i]] = true; } } 对于(var k in a) { diff.push (k); } 返回差异; } console.log (arr_diff ([a, b], [a, b, c, d '))); console.log (arr_diff(“abcd”、"中的")); console.log (arr_diff(“必杀技”,“必杀技”));
修正了一下最佳答案
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]]时,它将一个值从原始值转换为字符串,因此我们失去了实际值。
纯JavaScript解决方案(没有库) 与旧浏览器兼容(不使用过滤器) O (n ^ 2) 可选的fn回调参数,用于指定如何比较数组项
function diff(a, b, fn){ var max = Math.max(a.length, b.length); d = []; fn = typeof fn === 'function' ? fn : false for(var i=0; i < max; i++){ var ac = i < a.length ? a[i] : undefined bc = i < b.length ? b[i] : undefined; for(var k=0; k < max; k++){ ac = ac === undefined || (k < b.length && (fn ? fn(ac, b[k]) : ac == b[k])) ? undefined : ac; bc = bc === undefined || (k < a.length && (fn ? fn(bc, a[k]) : bc == a[k])) ? undefined : bc; if(ac == undefined && bc == undefined) break; } ac !== undefined && d.push(ac); bc !== undefined && d.push(bc); } return d; } alert( "Test 1: " + diff( [1, 2, 3, 4], [1, 4, 5, 6, 7] ).join(', ') + "\nTest 2: " + diff( [{id:'a',toString:function(){return this.id}},{id:'b',toString:function(){return this.id}},{id:'c',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}], [{id:'a',toString:function(){return this.id}},{id:'e',toString:function(){return this.id}},{id:'f',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}], function(a, b){ return a.id == b.id; } ).join(', ') );
快速的解决方案。尽管似乎其他人已经发布了相同方法的不同变体。我不确定这是否适合大型数组,但它适用于不大于10或15的数组。
差b - a
for(var i = 0; i < b.length; i++){
for(var j = 0; j < a.length; j ++){
var loc = b.indexOf(a[j]);
if(loc > -1){
b.splice(loc, 1);
}
}
}