12

I'm having some issues comparing the elements of two arrays and filtering out matching values. I only want to return array elements that are NOT included within 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 Answers 5

29

You can use filter and includes to achieve this:

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

var filteredKeywords = fullWordList.filter((word) => !wordsToRemove.includes(word));

console.log(filteredKeywords);

0
3

use filter and includes to perform this

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

That is pretty easy to do using 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
);
1

forEach on fullWordList is not required, use filter on fullWordList and indexOf() in your function in filter() to check if a number exists in wordsToRemove or not.

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

1

Perhaps you could try

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.