How to useforEach() and filter() in Javascript
Combining forEach()
and filter()
provides a straightforward approach to filter objects based on multiple properties. we will use foreach to iterate through the array and using filter method to filter the element of the array based on the condition. By filtering the element we are pushing that element into the new array.
Example: This example shows the use of the above approach.
JavaScript
const data = [ { id: 1, name: 'John' , age: 25 }, { id: 2, name: 'Jane' , age: 30 }, { id: 3, name: 'Doe' , age: 25 }, ]; // Filtering based on multiple // properties using forEach() and filter() const filteredData = []; data.forEach(item => { if (item.age === 25 && item.name === 'John' ) { filteredData.push(item); } }); console.log(filteredData); |
Output
[ { id: 1, name: 'John', age: 25 } ]
How to Filter an Array of Objects Based on Multiple Properties in JavaScript ?
Filtering an array of objects based on multiple properties is a common task in JavaScript. It allows us to selectively extract items from an array that satisfy specific conditions. We will explore different approaches to achieve this task.
These are the following approaches:
Table of Content
- Using the filter() Method
- Using a for Loop
- Using Array.from() and filter()
- Using reduce() method
- Using forEach() and filter()
- Using Array.filter() and Object.entries()
- Using Array.filter() and Object.keys()
Contact Us