有没有办法在JavaScript中返回两个数组之间的差值?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]发布于 2010-08-13 20:07:33
我想要一个类似的函数,它接受一个旧的数组和一个新的数组,并给我一个添加项的数组和一个删除项的数组,我希望它是高效的(所以没有.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};
}https://stackoverflow.com/questions/1187518
复制相似问题