Given an array of objects and a filter object, the goal is to filter and simplify the array based on multiple conditions specified in the filter. However, a specific issue arises when the filter contains multiple properties.
Consider the following code segment:
<code class="js">function filterUsers(users, filter) { var result = []; for (var prop in filter) { if (filter.hasOwnProperty(prop)) { // Iterate over the array for (var i = 0; i < filter.length; i++) { if (users[i][prop] === filter[prop]) { result.push(users[i]); } } } } return result; }
In the proposed solution, the problem occurs when the filter contains multiple properties. Specifically, during the second iteration, the comparison between users[i][prop] and filter[prop] is incorrect. To fix this, we can modify the code to the following:
<code class="js">function filterUsers(users, filter) { var result = []; for (var prop in filter) { if (filter.hasOwnProperty(prop)) { // Apply filter on the array users = users.filter((user) => user[prop] === filter[prop]); } } return result; }</code>
In this version, we utilize the built-in filter method of arrays to apply the filter conditions dynamically. This ensures that only objects that satisfy all specified conditions are included in the result.
With the updated solution, the filtering process will work as expected:
<code class="js">var users = [{ name: 'John', email: 'john@example.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@example.com', age: 35, address: 'England' }, { name: 'Mark', email: 'mark@example.com', age: 28, address: 'England' }]; var filter = { address: 'England', name: 'Mark' }; var filteredUsers = filterUsers(users, filter); console.log(filteredUsers); // Output: [{ name: 'Mark', email: 'mark@example.com', age: 28, address: 'England' }]</code>
This solution addresses the issue where multiple filter conditions were not being applied correctly, ensuring that the resulting filtered array accurately reflects the specified criteria.
The above is the detailed content of How to Filter a JavaScript Array of Objects Based on Multiple Conditions?. For more information, please follow other related articles on the PHP Chinese website!