如何在 JavaScript 中获取两个数组之间的差异? [英] How to get the difference between two arrays in JavaScript?
本文介绍了如何在 JavaScript 中获取两个数组之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 JavaScript 中返回两个数组之间的差异?
Is there a way to return the difference between two arrays in JavaScript?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
推荐答案
这个答案是 2009 年写的,所以有点过时了,对于理解问题也很有教育意义.我今天使用的最佳解决方案是
This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be
let difference = arr1.filter(x => !arr2.includes(x));
(此处感谢其他作者)
我假设您正在比较一个普通数组.如果没有,您需要将 for 循环更改为 for .. in 循环.
I assume you are comparing a normal array. If not, you need to change the for loop to a for .. in loop.
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
console.log(arr_diff("abcd", "abcde"));
console.log(arr_diff("zxc", "zxc"));
这篇关于如何在 JavaScript 中获取两个数组之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文