这个问题在这里已经有了答案:
How to get the difference between two arrays in JavaScript?
(81 个回答)
5年前关闭。
我有2个数组如下。我想比较两个数组,只提供“检查”中不存在于“数据”数组中的元素。
var check= ["044", "451"],
data = ["343", "333", "044", "123", "444", "555"];
使用的功能如下。此函数将导致提供存在于“数据”数组中的“检查”数组中的元素
function getMatch(a, b) {
var matches = [];
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i] === b[e] ) matches.push( a[i] );
}
}
return matches;
}
getMatch(check, data); // ["044"] ---> this will be the answer as '044' is only present in 'data'
我想要一个“数据”数组中不存在的元素列表。有人可以让我知道如何实现这一目标。
最佳答案
您可以使用 filter
和 Set
,提供Set
作为 filter
的上下文方法,所以它可以作为 this
访问:
var check= ["044", "451"],
data = ["343", "333", "044", "123", "444", "555"];
var res = check.filter( function(n) { return !this.has(n) }, new Set(data) );
console.log(res);
请注意,这在 O(n) 时间内运行,与
indexOf
相反。/includes
基于解决方案,它真正代表一个嵌套循环。
关于javascript - 比较 2 个数组并显示数组 1 中不匹配的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40537972/