The filter array is not in another array

You need to filter one array based on another array. Is there a disposal function in the knockout? otherwise i need to go with javascript

First:

var obj1 = [{ "visible": "true", "id": 1 }, { "visible": "true", "id": 2 }, { "visible": "true", "id": 3 }, { "Name": "Test3", "id": 4 }]; 

The second:

 var obj2 = [ 2,3] 

Now I need to filter obj1 based on obj2 and return elements from obj1 that are not in obj2 omittng 2,3 in the above data (Comparison on object 1 Id )

output:

 [{ "visible": "true", "id": 1 }, { "Name": "Test3", "id": 4 }]; 
+15
source share
2 answers

You can simply run obj1 with filter and use indexOf on obj2 to see if it exists. indexOf returns -1 if the value is not in the array, and filter turns on the element when the callback returns true .

 var arr = obj1.filter(function(item){ return obj2.indexOf(item.id) === -1; }); 

With the newer ES and API syntax, this becomes easier:

 const arr = obj1.filter(i => obj2.includes(i.id)) 
+33
source

To create your output array, create a function that will iterate through obj1 and populate a new array based on whether the id of all obj objects exists in the iteration in obj2.

 var obj1 = [{ "visible": "true", "id": 1 }, { "visible": "true", "id": 2 }, { "visible": "true", "id": 3 }, { "Name": "Test3", "id": 4 }]; var obj2 = [2,3] var select = function(arr) { var newArr = []; obj1.forEach(function(obj) { if obj2.indexOf(obj.id) !== -1 { newArr.push(obj) }; }; return newArr; }; 
0
source

All Articles