javascript - 比较 2 个数组并显示数组 1 中不匹配的元素

标签 javascript arrays loops

这个问题在这里已经有了答案:





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'

我想要一个“数据”数组中不存在的元素列表。有人可以让我知道如何实现这一目标。

最佳答案

您可以使用 filterSet ,提供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/

相关文章:

javascript - 如何获取值作为类型并将其添加到一个文本区域中?

javascript - moment.js isoWeek 不适用于 Heroku 实例

c++ - 我的 for 循环使每个值成为最后一个值 (C++)

c - 我是否使用循环来迭代小尺寸数组(例如 2 或 3)?

python - 这个循环方法正确吗? Python 3.4.3

javascript - 浏览器调整大小后重新计算宽度

javascript - JQuery - 使用 'this' 通过一个函数显示和隐藏 DIV

php - 将多个 SELECT 标签的输入存储到 PHP 数组中

arrays - 将元素保存在Map/Array/Collection中……Grails

R:如何将递归或迭代函数/映射输出输出到向量中?