是否有一种方法可以在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"]
当前回答
如果数组不是简单类型,则可以采用上面的答案之一:
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.map(function(e) { return JSON.stringify(e); }).indexOf(JSON.stringify(i)) < 0;});
};
这种方法适用于复杂对象的数组。
其他回答
var result = [];
var arr1 = [1,2,3,4];
var arr2 = [2,3];
arr1.forEach(function(el, idx) {
function unEqual(element, index, array) {
var a = el;
return (element!=a);
}
if (arr2.every(unEqual)) {
result.push(el);
};
});
alert(result);
困难的方法(如果你想做一些比.indexOf更奇特的东西)
var difference = function (source, target) {
return source.reduce(function (diff, current) {
if (target.indexOf(current) === -1) {
diff.push(current);
}
return diff;
}, []);
}
简单的方法
var difference = function (source, target) {
return source.filter(function (current) {
return target.indexOf(current) === -1;
});
}
const difference = function (baseArray, arrayToCampare, callback = (a, b) => a!== b) {
if (!(arrayToCampare instanceof Array)) {
return baseArray;
}
return baseArray.filter(baseEl =>
arrayToCampare.every(compareEl => callback(baseEl, compareEl)));
}
类似于Ian Grainger的解决方案(但在打字稿中):
function findDiffs(arrayOne: string[], arrayTwo: string[]) {
let onlyInArrayOne = []
let onlyInArrayTwo = []
let share = []
let [arrayOneCopy, arrayTwoCopy] = [[...arrayOne], [...arrayTwo]]
arrayOneCopy.sort(); arrayTwoCopy.sort()
while (arrayOneCopy.length !== 0 && arrayTwoCopy.length !== 0) {
if (arrayOneCopy[0] == arrayTwoCopy[0]) {
share.push(arrayOneCopy[0])
arrayOneCopy.splice(0, 1)
arrayTwoCopy.splice(0, 1)
}
if (arrayOneCopy[0] < arrayTwoCopy[0]) {
onlyInArrayOne.push(arrayOneCopy[0])
arrayOneCopy.splice(0, 1)
}
if (arrayOneCopy[0] > arrayTwoCopy[0]) {
onlyInArrayTwo.push(arrayTwoCopy[0])
arrayTwoCopy.splice(0, 1)
}
}
onlyInArrayTwo = onlyInArrayTwo.concat(arrayTwoCopy)
onlyInArrayOne = onlyInArrayOne.concat(arrayOneCopy)
return {
onlyInArrayOne,
onlyInArrayTwo,
share,
diff: onlyInArrayOne.concat(onlyInArrayTwo)
}
}
// arrayOne: [ 'a', 'b', 'c', 'm', 'y' ]
// arrayTwo: [ 'c', 'b', 'f', 'h' ]
//
// Results:
// {
// onlyInArrayOne: [ 'a', 'm', 'y' ],
// onlyInArrayTwo: [ 'f', 'h' ],
// share: [ 'b', 'c' ],
// diff: [ 'a', 'm', 'y', 'f', 'h' ]
// }
还有另一个答案,但似乎没有人提到jsperf,他们比较了几种算法和技术支持:https://jsperf.com/array-difference-javascript似乎使用过滤器得到了最好的结果。谢谢