Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Array Not in Another Array

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
}];
like image 321
Peru Avatar asked Nov 07 '15 00:11

Peru


People also ask

How do you get the elements of one array which are not present in another array using JavaScript?

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.

How do I filter two arrays?

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.

How do you filter an array from all elements of another array object?

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'}];

How do you remove one array from another array?

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.


1 Answers

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)) 
like image 168
Joseph Avatar answered Sep 29 '22 22:09

Joseph