Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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);
like image 975
Pyreal Avatar asked Aug 09 '17 20:08

Pyreal


People also ask

How can I find non matching values in two arrays?

JavaScript finding non-matching values in two arrays The code will look like this. const array1 = [1, 2, 3, 4, 5, 6]; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const output = array2. filter(function (obj) { return array1. indexOf(obj) === -1; }); console.

How do you compare two arrays if they are equal or not?

Check if two arrays are equal or not using Sorting Follow the steps below to solve the problem using this approach: Sort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.


1 Answers

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);
like image 135
Alberto Trindade Tavares Avatar answered Sep 29 '22 00:09

Alberto Trindade Tavares