[英]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);
使用过滤器和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);
forEach
上fullWordList
不是必需的,使用filter
上fullWordList
和indexOf()
在你的函数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.