Need to filter one array based on another array. Is there a util function in knock out ? else 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
}];
Second :
var obj2 = [ 2,3]
Now i need to filter obj1 based on obj2 and return items 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
}];
To create your output array, create a function that will iterate through obj1 and populate a new array based on whether the id of every obj in the iteration exists in obj2.
You can simply run through
obj1
usingfilter
and useindexOf
onobj2
to see if it exists.indexOf
returns-1
if the value isn't in the array, andfilter
includes the item when the callback returnstrue
.With newer ES syntax and APIs, it becomes simpler: