繁体   English   中英

使用.filter比较两个数组并返回不匹配的值

[英]Using .filter to compare two arrays and return values that aren't matched

我在比较两个数组的元素并过滤掉匹配值时遇到了一些问题。 我只想返回不包含在wordsToRemove数组元素。

var fullWordList = ['1','2','3','4','5'];
var wordsToRemove = ['1','2','3'];

var filteredKeywords = fullWordList.forEach(function(fullWordListValue) {
    wordsToRemove.filter(function(wordsToRemoveValue) {
        return fullWordListValue !== wordsToRemoveValue
    })
});

console.log(filteredKeywords);

您可以使用filterincludes来实现此目的:

 var fullWordList = ['1','2','3','4','5']; var wordsToRemove = ['1','2','3']; var filteredKeywords = fullWordList.filter((word) => !wordsToRemove.includes(word)); console.log(filteredKeywords); 

使用过滤器和include来执行此操作

 var fullWordList = ['1','2','3','4','5']; var wordsToRemove = ['1','2','3']; var newList = fullWordList.filter(function(word){ return !wordsToRemove.includes(word); }) console.log(newList); 

forEachfullWordList不是必需的,使用filterfullWordListindexOf()在你的函数filter()以检查是否存在一些wordsToRemove与否。

 var fullWordList = ['1','2','3','4','5']; var wordsToRemove = ['1','2','3']; var newList = fullWordList.filter(function(x){ return wordsToRemove.indexOf(x) < 0; }) console.log(newList); 

使用Array.prototype.filter很容易做到:

var fullWordList = ['1','2','3','4','5'];
var wordsToRemove = ['1','2','3'];

var filteredKeywords = fullWordList.filter(
  word=>!wordsToRemove.includes(word)
//or
//word=>wordsToRemove.indexOf(word)<0
);

也许你可以试试

var fullWordList = ['1','2','3','4','5'];
var wordsToRemove = ['1','2','3'];
var match = [];

for(let word of fullWordList){
    if(!wordsToRemove.find((val) => val == word))match.push(word);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM