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

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

本文介绍了比较2个数组并显示数组1中不匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个数组,如下所示.我想比较两个数组,只提供检查"中不存在于数据"数组中的元素.

I have 2 arrays as follows. I want to compare both arrays and only provide the elements from 'check' which are not present in 'data' array.

var check= ["044", "451"],
data = ["343", "333", "044", "123", "444", "555"];

使用的功能如下.此功能将导致提供检查"数组中存在于数据"数组中的元素

The function used is as follows. This function will result in providing the elements in 'check' array which are present in 'data' array

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'

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

I want to have a list of elements which are not present in 'data' array. Can someone let me know how to achieve this.

推荐答案

您可以使用filterSet,将Set作为上下文提供给filter方法,因此可以将其作为:

You could use filter and Set, providing the Set as context to the filter method, so it can be accessed as 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的解决方案相反,后者实际上代表了嵌套循环.

Note that this runs in O(n) time, contrary to indexOf/includes based solutions, which really represent a nested loop.

这篇关于比较2个数组并显示数组1中不匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:08