【发布时间】:2017-03-25 02:14:25
【问题描述】:
我有 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'
我想要一个“数据”数组中不存在的元素列表。有人可以让我知道如何实现这一目标。
【问题讨论】:
-
JavaScript array difference 似乎与您要查找的内容非常接近...,
-
var notPresent = check.filter(function(item) { return data.indexOf(item) < 0; }); -
还有——上面的代码更简单
function getMatch(a, b) { return a.filter(function(item) { return b.indexOf(item) >= 0; });}
标签: javascript arrays loops