是否有一种方法可以在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"]
当前回答
下面是另一个可以返回差异的解决方案,就像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}
其他回答
贡献一个jQuery解决方案,我目前正在使用:
if (!Array.prototype.diff) {
Array.prototype.diff = function (a) {
return $.grep(this, function (i) { return $.inArray(i, a) === -1; });
};
}
Samuel:“对于我的代码,我也需要删除副本,但我想这并不总是可取的。 我想主要的缺点是它可能会比较许多已经被拒绝的选择。”
当比较TWO列表、数组等,且元素小于1000时,行业标准中的 3GL世界是使用冒泡排序,以避免欺骗。
代码看起来像这样……(未经测试,但应该有效)
var Array01=new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P');
var Array02=new Array('X','B','F','W','Z','X','J','P','P','O','E','N','Q');
var Array03=Array01;
for(x=1; x<Array02.length; x++) {
for(y=0; y<Array01.length-1; y++) {
if (Array01[y]==Array02[x]) {Array03.splice(y,1);}}}
Array01=Array03;
要测试输出…
for(y=0; y<Array01.length; y++) {document.write(Array01[y])}
Array.prototype.difference = function(e) {
return this.filter(function(i) {return e.indexOf(i) < 0;});
};
eg:-
[1,2,3,4,5,6,7].difference( [3,4,5] );
=> [1, 2, 6 , 7]
ES2015的函数方法
计算两个数组之间的差值是Set操作之一。这个术语已经表明应该使用本机Set类型,以便提高查找速度。不管怎样,当你计算两个集合之间的差值时,有三种排列:
[+left difference] [-intersection] [-right difference]
[-left difference] [-intersection] [+right difference]
[+left difference] [-intersection] [+right difference]
下面是反映这些排列的功能性解决方案。
离开的区别:
// small, reusable auxiliary functions const apply = f => x => f(x); const flip = f => y => x => f(x) (y); const createSet = xs => new Set(xs); const filter = f => xs => xs.filter(apply(f)); // left difference const differencel = xs => ys => { const zs = createSet(ys); return filter(x => zs.has(x) ? false : true ) (xs); }; // mock data const xs = [1,2,2,3,4,5]; const ys = [0,1,2,3,3,3,6,7,8,9]; // run the computation console.log( differencel(xs) (ys) );
正确的区别:
差异是微不足道的。这与翻转的参数不同。为了方便,你可以写一个函数:const differencer = flip(difference)。这是所有!
对称的区别:
现在我们有了左边和右边,实现对称的差异也变得微不足道:
// small, reusable auxiliary functions const apply = f => x => f(x); const flip = f => y => x => f(x) (y); const concat = y => xs => xs.concat(y); const createSet = xs => new Set(xs); const filter = f => xs => xs.filter(apply(f)); // left difference const differencel = xs => ys => { const zs = createSet(ys); return filter(x => zs.has(x) ? false : true ) (xs); }; // symmetric difference const difference = ys => xs => concat(differencel(xs) (ys)) (flip(differencel) (xs) (ys)); // mock data const xs = [1,2,2,3,4,5]; const ys = [0,1,2,3,3,3,6,7,8,9]; // run the computation console.log( difference(xs) (ys) );
我想这个例子是一个很好的起点,可以让你了解函数式编程的含义:
使用可以以许多不同方式组合在一起的构建块进行编程。
这个答案是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(“必杀技”,“必杀技”));