This blog will describe how to filter an array object with another array of objects.
How to Filter an Array of Objects With Another Array of Objects Using JavaScript?
The array of objects can be filtered with another array of objects using the “filter()” and “some()” methods in combination.
The filter() method creates a new array having elements that pass a particular test provided by a function. The some() method verifies if the array elements pass a particular test. These methods can be applied to filter the arrays of objects and fetch the elements from both arrays based on a particular condition via the strict equality(===) operator:
Example
Let’s go through the below-stated example to understand the stated concept:
const firstArray = [
{ month: 1, monName: 'January' },
{ month: 2, monName: 'February' },
{ month: 3, monName: 'March' }
];
const secondArray = [
{ month: 1, monName: 'January' },
{ month: 2, monName: 'February' },
{ month: 4, monName: 'April' }
];
const thirdArray = firstArray.filter((elem) => {
return secondArray.some((ele) => {
return ele.month === elem.month&& ele.monName === elem.monName;
});
});
console.log(thirdArray);
</script>
In this code block:
- Firstly, create an array of objects named “firstArray” having the stated elements in the form of “key-value” pairs.
- Likewise, create another objects array named “secondArray” having the values in the same format.
- Now, create another array named “thirdArray”.
- Here, associate the “filter()” method with the “firstArray” by referring to its elements.
- Similarly, apply the “some()” method and point to the elements in the associated array.
- Return the values from both arrays which satisfy the stated condition via the strict equality operator (===).
- It is such that the common values from both the arrays against the keys “month, monName” will be returned.
Output
The output shows that the common values against the particular keys are returned.
Conclusion
To filter an array of objects with another array of objects in JavaScript, use the “filter()” method and “some()” method in combination. It is such that the former method is applied on the first array and the latter method upon the second array such that the values passing the provided test are returned. This blog discussed the procedure for filtering an object’s array with another object’s array using JavaScript.