是否有一种方法可以在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"]
当前回答
我在这里读到的答案有很多问题,使得它们在实际编程应用中价值有限。
First and foremost, you're going to want to have a way to control what it means for two items in the array to be "equal". The === comparison is not going to cut it if you're trying to figure out whether to update an array of objects based on an ID or something like that, which frankly is probably one of the most likely scenarios in which you will want a diff function. It also limits you to arrays of things that can be compared with the === operator, i.e. strings, ints, etc, and that's pretty much unacceptable for grown-ups.
其次,diff操作有三种状态结果:
在第一个数组中但不在第二个数组中的元素 两个数组共用的元素 在第二个数组中但不在第一个数组中的元素
我认为这意味着你需要不少于2个循环,但我愿意接受肮脏的技巧,如果有人知道如何将其减少到一个。
这里是我拼凑的一些东西,我想强调的是,我绝对不在乎它在旧版本的Microshaft浏览器中不起作用。如果您在IE这样的较差的编码环境中工作,那么您就可以自行修改它,使其在您无法满意的限制范围内工作。
Array.defaultValueComparison = function(a, b) {
return (a === b);
};
Array.prototype.diff = function(arr, fnCompare) {
// validate params
if (!(arr instanceof Array))
arr = [arr];
fnCompare = fnCompare || Array.defaultValueComparison;
var original = this, exists, storage,
result = { common: [], removed: [], inserted: [] };
original.forEach(function(existingItem) {
// Finds common elements and elements that
// do not exist in the original array
exists = arr.some(function(newItem) {
return fnCompare(existingItem, newItem);
});
storage = (exists) ? result.common : result.removed;
storage.push(existingItem);
});
arr.forEach(function(newItem) {
exists = original.some(function(existingItem) {
return fnCompare(existingItem, newItem);
});
if (!exists)
result.inserted.push(newItem);
});
return result;
};
其他回答
下划线中的差分方法(或它的替换,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]);
要从另一个数组中减去一个数组,只需使用下面的代码片段:
var a1 = ['1','2','3','4','6'];
var a2 = ['3','4','5'];
var items = new Array();
items = jQuery.grep(a1,function (item) {
return jQuery.inArray(item, a2) < 0;
});
它将返回['1,'2','6'],这些是第一个数组中不存在的项。
因此,根据您的问题示例,以下代码是准确的解决方案:
var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];
var _array = new Array();
_array = jQuery.grep(array2, function (item) {
return jQuery.inArray(item, array1) < 0;
});
一个衬垫
const unique = (a) => [...new Set(a)]; const uniqueBy = (x,f)=>Object.values(x.reduce((a,b)=>((a[f(b)]=b),a),{})); const intersection = (a, b) => a.filter((v) => b.includes(v)); const diff = (a, b) => a.filter((v) => !b.includes(v)); const symDiff = (a, b) => diff(a, b).concat(diff(b, a)); const union = (a, b) => diff(a, b).concat(b); const a = unique([1, 2, 3, 4, 5, 5]); console.log(a); const b = [4, 5, 6, 7, 8]; console.log(intersection(a, b), diff(a, b), symDiff(a, b), union(a, b)); console.log(uniqueBy( [ { id: 1, name: "abc" }, { id: 2, name: "xyz" }, { id: 1, name: "abc" }, ], (v) => v.id )); const intersectionBy = (a, b, f) => a.filter((v) => b.some((u) => f(v, u))); console.log(intersectionBy( [ { id: 1, name: "abc" }, { id: 2, name: "xyz" }, ], [ { id: 1, name: "abc" }, { id: 3, name: "pqr" }, ], (v, u) => v.id === u.id )); const diffBy = (a, b, f) => a.filter((v) => !b.some((u) => f(v, u))); console.log(diffBy( [ { id: 1, name: "abc" }, { id: 2, name: "xyz" }, ], [ { id: 1, name: "abc" }, { id: 3, name: "pqr" }, ], (v, u) => v.id === u.id ));
打印稿
操场上的链接
const unique = <T>(array: T[]) => [...new Set(array)];
const intersection = <T>(array1: T[], array2: T[]) =>
array1.filter((v) => array2.includes(v));
const diff = <T>(array1: T[], array2: T[]) =>
array1.filter((v) => !array2.includes(v));
const symDiff = <T>(array1: T[], array2: T[]) =>
diff(array1, array2).concat(diff(array2, array1));
const union = <T>(array1: T[], array2: T[]) =>
diff(array1, array2).concat(array2);
const intersectionBy = <T>(
array1: T[],
array2: T[],
predicate: (array1Value: T, array2Value: T) => boolean
) => array1.filter((v) => array2.some((u) => predicate(v, u)));
const diffBy = <T>(
array1: T[],
array2: T[],
predicate: (array1Value: T, array2Value: T) => boolean
) => array1.filter((v) => !array2.some((u) => predicate(v, u)));
const uniqueBy = <T>(
array: T[],
predicate: (v: T, i: number, a: T[]) => string
) =>
Object.values(
array.reduce((acc, value, index) => {
acc[predicate(value, index, array)] = value;
return acc;
}, {} as { [key: string]: T })
);
这个答案是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(“必杀技”,“必杀技”));
这是工作的:基本上合并两个数组,寻找重复的,并将没有重复的推入一个新数组,这是差异。
函数diff(arr1, arr2) { var newArr = []; Var arr = ar1 .concat(arr2); For (var I in arr){ Var f = arr[i]; Var t = 0; (j = 0;j < arr.length;j + +) { If (arr[j] === f){ t + +; } } 如果(t == 1){ newArr.push (f); } } 返回newArr; }