How to Filter an Array from All Elements of Another Array

How to filter an array from all elements of another array

You can use the this parameter of the filter() function to avoid to store your filter array in a global variable.

var filtered = [1, 2, 3, 4].filter(    function(e) {      return this.indexOf(e) < 0;    },    [2, 4]);console.log(filtered);

How to do a partial match filter on an array from all elements of another array

To do partal matching just need parse int to string

const arr1 = [{categories: 292300}, {categories: 300}, {categories: 292500280}];
const arr2 = [300, 498];

const result = arr1.filter(({ categories }) =>
arr2.some((e) => String(categories).includes(String(e))));

console.log(result);
.as-console-wrapper {max-height: 100% !important; top: 0}

How to filter an array with elements of another array?

Check if .every of the banned words are not included in the comment you're iterating over. Make sure to call toLowerCase on the comment first:

const comments = ["Very useful tutorial, thank you so much!", "React is not a damn framework, it's a LIBRARY",  "Why you put bloody kitten pictures in a tech tutorial is beyond me!", "Which one is better, React or Angular?", 'There is no "better", it depends on your use case, DAMN YOU'];const bannedWords = ['bloody', 'damn'];
const result = comments.filter(comment => bannedWords.every(word => !comment.toLowerCase().includes(word)))console.log(result);

Filter array of objects with another array of objects

var filtered = [];

for(var arr in myArray){
for(var filter in myFilter){
if(myArray[arr].userid == myFilter[filter].userid && myArray[arr].projectid == myFilter[filter].projectid){
filtered.push(myArray[arr].userid);
}
}
}
console.log(filtered);

Remove all elements contained in another array

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
return toRemove.indexOf( el ) < 0;
} );

Small improvement, as browser support for Array.includes() has increased:

myArray = myArray.filter( function( el ) {
return !toRemove.includes( el );
} );

Next adaptation using arrow functions:

myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

Filter Array if elements are in another Array

array1.filter( element => !array2.includes( element ) ); 


Related Topics



Leave a reply



Submit