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);
var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter(myCallBack);
function myCallBack(el){
return anotherOne.indexOf(el) < 0;
}
In the callback, you check if each value of array
is in anotherOne
https://jsfiddle.net/0tsyc1sx/
If you are using lodash.js
, use _.difference
filteredArray = _.difference(array, anotherOne);
Demo
If you have an array of objects :
var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];
var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];
var filteredArray = array.filter(function(array_el){
return anotherOne.filter(function(anotherOne_el){
return anotherOne_el.id == array_el.id;
}).length == 0
});
Demo array of objects
Demo diff array of objects with lodash
I would do as follows;
var arr1 = [1,2,3,4],
arr2 = [2,4],
res = arr1.filter(item => !arr2.includes(item));
console.log(res);