Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria.
Below are the approaches to filter an array of objects with another array of objects in JavaScript:
Table of Content
Using filter and includes Methods
In this approach, we are using the filter method combined with includes to create a filteredArray that contains objects from mainArray whose IDs are present in filterArray.
Syntax:
let newArray = arrayToFilter.filter(item => arrayToCheck.includes(item));
Example: The below example uses the filter and includes Methods to Filter an array of objects with another array of objects in JavaScript.
let mainArray = [{
id: 1,
name: 'Sandip'
},
{
id: 2,
name: 'Mandip'
},
{
id: 3,
name: 'Praveen'
}
];
let filterArray = [{
id: 1
},
{
id: 3
}
];
let filteredArray = mainArray
.filter(item => filterArray
.map(x => x.id)
.includes(item.id));
console.log(filteredArray);
Output
[ { id: 1, name: 'Sandip' }, { id: 3, name: 'Praveen' } ]
Using Looping
In this approach, we are using nested loops to iterate through mainArray and filterArray, comparing IDs to create res containing objects with matching IDs from mainArray and filterArray.
Syntax:
let filteredArray = [];
for (let item of arrayToFilter) {
if (arrayToCheck.includes(item)) {
filteredArray.push(item);
}
}
Example: The below example uses Looping to Filter array of objects with another array of objects in JavaScript.
let mainArray = [{
id: 1,
name: 'Sandip'
},
{
id: 2,
name: 'Mandip'
},
{
id: 3,
name: 'Praveen'
}
];
let filterArray = [{
id: 1
},
{
id: 3
}
];
let res = [];
for (let item of mainArray) {
for (let filterItem of filterArray) {
if (item.id === filterItem.id) {
res.push(item);
break;
}
}
}
console.log(res);
Output
[ { id: 1, name: 'Sandip' }, { id: 3, name: 'Praveen' } ]