"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Filter a JavaScript Array of Objects Based on Multiple Conditions?

How to Filter a JavaScript Array of Objects Based on Multiple Conditions?

Published on 2024-11-08
Browse:305

How to Filter a JavaScript Array of Objects Based on Multiple Conditions?

Filtering Arrays in JavaScript Based on Multiple Conditions

Problem Statement

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.

Proposed Solution

Consider the following code segment:

function filterUsers(users, filter) {
  var result = [];
  for (var prop in filter) {
    if (filter.hasOwnProperty(prop)) {
      // Iterate over the array
      for (var i = 0; i 

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:

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

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.

Example Usage

With the updated solution, the filtering process will work as expected:

var users = [{
  name: 'John',
  email: '[email protected]',
  age: 25,
  address: 'USA'
}, {
  name: 'Tom',
  email: '[email protected]',
  age: 35,
  address: 'England'
}, {
  name: 'Mark',
  email: '[email protected]',
  age: 28,
  address: 'England'
}];

var filter = {
  address: 'England',
  name: 'Mark'
};

var filteredUsers = filterUsers(users, filter);

console.log(filteredUsers); // Output: [{ name: 'Mark', email: '[email protected]', age: 28, address: 'England' }]

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3