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
}];
Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.
const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4]; const arr2 = [4, 56, 23]; We are required to write a JavaScript function that takes in these two arrays and filters the first to contain only those elements that are not present in the second array. And then return the filtered array.
Filter an array containing objects based on another array containing objects in JavaScript. const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}]; const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.
You can simply run through obj1
using filter
and use indexOf
on obj2
to see if it exists. indexOf
returns -1
if the value isn't in the array, and filter
includes the item when the callback returns true
.
var arr = obj1.filter(function(item){ return obj2.indexOf(item.id) === -1; });
With newer ES syntax and APIs, it becomes simpler:
const arr = obj1.filter(i => !obj2.includes(i.id))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With