Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Filter array of objects by a specific property in JavaScript?
Filtering arrays of objects by specific properties is a common task in JavaScript. While the article shows using map() with a ternary operator for comparison, the filter() method is typically more appropriate for filtering operations.
Basic Array Filtering with filter()
The filter() method creates a new array with elements that pass a test condition:
let customers = [
{firstName: 'John', amount: 100},
{firstName: 'David', amount: 50},
{firstName: 'Bob', amount: 80},
{firstName: 'Alice', amount: 120}
];
// Filter customers with amount greater than 75
let highValueCustomers = customers.filter(customer => customer.amount > 75);
console.log(highValueCustomers);
[
{ firstName: 'John', amount: 100 },
{ firstName: 'Bob', amount: 80 },
{ firstName: 'Alice', amount: 120 }
]
Comparing Two Arrays (Original Approach)
The original example compares two arrays and selects objects with higher amounts using map():
let firstCustomerDetails = [
{firstName: 'John', amount: 100},
{firstName: 'David', amount: 50},
{firstName: 'Bob', amount: 80}
];
let secondCustomerDetails = [
{firstName: 'John', amount: 400},
{firstName: 'David', amount: 70},
{firstName: 'Bob', amount: 40}
];
var output = firstCustomerDetails.map((key, position) =>
key.amount > secondCustomerDetails[position].amount ? key :
secondCustomerDetails[position]
);
console.log(output);
[
{ firstName: 'John', amount: 400 },
{ firstName: 'David', amount: 70 },
{ firstName: 'Bob', amount: 80 }
]
Multiple Filter Conditions
You can combine multiple conditions when filtering:
let customers = [
{firstName: 'John', amount: 100, status: 'active'},
{firstName: 'David', amount: 50, status: 'inactive'},
{firstName: 'Bob', amount: 80, status: 'active'},
{firstName: 'Alice', amount: 120, status: 'active'}
];
// Filter active customers with amount > 75
let filteredCustomers = customers.filter(customer =>
customer.status === 'active' && customer.amount > 75
);
console.log(filteredCustomers);
[
{ firstName: 'John', amount: 100, status: 'active' },
{ firstName: 'Bob', amount: 80, status: 'active' },
{ firstName: 'Alice', amount: 120, status: 'active' }
]
Method Comparison
| Method | Purpose | Returns |
|---|---|---|
filter() |
Filter elements based on condition | New array with filtered elements |
map() |
Transform each element | New array with same length |
Conclusion
Use filter() for filtering operations and map() for transformations. The filter() method provides cleaner, more readable code when you need to select objects based on property values.
Advertisements
