How to filter an array from all elements of another array
I'd like to understand the best way to filter an array from all elements of another one. I tried with the filter function, but it doesn't come to me how to give it the values i want to remove.
Something Like:
var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter(myCallback);
// filteredArray should now be [1,3]
function myCallBack(){
return element ! filteredArray;
//which clearly can't work since we don't have the reference <,<
}
in case the filter function is not usefull, how would you implement this ?
Edit: i checked the possible duplicate question, and it could be useful for those who understand javascript easily. The answer checked as good makes things easy.
Solution 1:
I would do as follows;
var arr1 = [1,2,3,4],
arr2 = [2,4],
res = arr1.filter(item => !arr2.includes(item));
console.log(res);
Solution 2:
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);