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

时间:2017-08-09 20:06:54

标签: javascript

我在比较两个数组的元素并过滤掉匹配值时遇到了一些问题。我只想返回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);

5 个答案:

答案 0 :(得分:10)

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

public function downloadAction()
{
    $filename = str_replace('..', '', $this->params('filename'));
    $file     = 'data/' . $filename;

    if (false === file_exists($file)) {
        return $this->redirect('routename-file-does-not-exist');
    }

    $filetype = finfo_file($file);
    $response = new \Zend\Http\Response\Stream();
    $response->getHeaders()->addHeaders(array(
        'Content-Type' => $filetype,
        'Content-Disposition' => "attachement; filename=\"$filename\""
    ));
    $response->setStream(fopen($wpFilePath, 'r'));
    return $response;
}

答案 1 :(得分:2)

使用过滤器和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);

答案 2 :(得分:1)

forEach上{p} fullWordList不是必需的,请filter中的fullWordListindexOf()中的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);或不存在。

&#13;
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 3 :(得分:1)

使用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
);

答案 4 :(得分:1)

也许你可以试试

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);
}