是否有一种方法可以在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"]
当前回答
如果你的数组包含对象,如果你想比较一个属性,就会变得有点困难。
幸运的是,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}]
其他回答
随着ES6的到来,带有sets和splat操作符(当时只在Firefox中工作,请检查兼容性表),你可以编写以下一行代码:
var a = ['a', 'b', 'c', 'd'];
var b = ['a', 'b'];
var b1 = new Set(b);
var difference = [...new Set(a.filter(x => !b1.has(x)))];
结果是["c", "d"]。
如果你的数组包含对象,如果你想比较一个属性,就会变得有点困难。
幸运的是,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}]
我在这里读到的答案有很多问题,使得它们在实际编程应用中价值有限。
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;
};
你可以使用underscore.js: http://underscorejs.org/#intersection
你需要数组的方法:
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
我想要一个类似的函数,它接受一个旧数组和一个新数组,并给我一个添加项的数组和一个删除项的数组,我希望它是有效的(所以没有.contains!)。
你可以在这里尝试我提出的解决方案:http://jsbin.com/osewu3/12。
有人能看出算法的问题或改进吗?谢谢!
代码清单:
function diff(o, n) {
// deal with empty lists
if (o == undefined) o = [];
if (n == undefined) n = [];
// sort both arrays (or this won't work)
o.sort(); n.sort();
// don't compare if either list is empty
if (o.length == 0 || n.length == 0) return {added: n, removed: o};
// declare temporary variables
var op = 0; var np = 0;
var a = []; var r = [];
// compare arrays and add to add or remove lists
while (op < o.length && np < n.length) {
if (o[op] < n[np]) {
// push to diff?
r.push(o[op]);
op++;
}
else if (o[op] > n[np]) {
// push to diff?
a.push(n[np]);
np++;
}
else {
op++;np++;
}
}
// add remaining items
if( np < n.length )
a = a.concat(n.slice(np, n.length));
if( op < o.length )
r = r.concat(o.slice(op, o.length));
return {added: a, removed: r};
}