【问题标题】:Compare 2 arrays and show unmatched elements from array 1 [duplicate]比较2个数组并显示数组1中不匹配的元素[重复]
【发布时间】: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) &lt; 0; });
  • 还有——上面的代码更简单function getMatch(a, b) { return a.filter(function(item) { return b.indexOf(item) &gt;= 0; });}

标签: javascript arrays loops


【解决方案1】:

您可以使用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 的解决方案相反,后者实际上代表了一个嵌套循环。

【讨论】:

  • 这个解决方案很有帮助,但如果我有要比较的对象数组怎么办?您能为这种情况提供解决方案吗?
  • 当然,这是可能的。看看答案here
  • 太好了..感谢您的快速回复
  • 不客气 ;-)
【解决方案2】:

有很多方法可以实现这一点,但我会保持你的编码风格。在嵌套循环之前将匹配标志设置为 false,如果找到匹配,则在嵌套循环中将其设置为 true,在嵌套循环之后检查您的标志是否为 false,然后将元素推送到缺少的数组中。

function getMissing(a, b) {
    var missings = [];
    var matches = false;

    for ( var i = 0; i < a.length; i++ ) {
        matches = false;
        for ( var e = 0; e < b.length; e++ ) {
            if ( a[i] === b[e] ) matches = true;
        }
        if(!matches) missings.push( a[i] );
    }
    return missings;
}

【讨论】:

  • 我想知道被否决的原因! :)
【解决方案3】:

您可以为此使用indexOffilter

check.filter((item) => { 
  return data.indexOf(item) === -1 
})

【讨论】:

  • 很公平,这里没有箭头函数:check.filter(function(item) { return data.indexOf(item) === -1 }) 这里包含:check.filter((item) => { return !data.includes(item) }) ;-)
【解决方案4】:

编辑

.find() 方法,正如评论中提到的,只返回一个满足给定谓词函数的单个值。要更正此问题,只需将 .find() 替换为 .filter() 函数,它应该可以按预期工作。谢谢你的收获。

如果你熟悉 ES6,可以使用特制的.find()Array 方法;毕竟,它是为所描述的情况而提供的。它接受一个谓词函数并从数组.find() 中返回满足谓词函数参数的值(这里是check)。在我的代码中,谓词函数只是检查data 数组中不存在的值。 .includes() 同样是最新的 ES6 JavaScript 规范的产物,返回一个布尔值。

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

let notPresentInData = check.filter(val => !data.includes(val));
console.log(notPresentInData);

【讨论】:

  • “它...返回值”:find 返回 one 值,而不是数组,正如您在 sn-p 的输出中看到的那样。
  • 不错的收获。我用filter 替换了find...认为可以解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多