- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter array of objects by a specific property in JavaScript?
Use the concept of map() along with ternary operator (?). Following are our array of objects −
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} ];
Let’s say, we need to filter array of objects by amount property. The one with the greatest amount is considered.
Example
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);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo83.js.
Output
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo83.js [ { firstName: 'John', amount: 400 }, { firstName: 'David', amount: 70 }, { firstName: 'Bob', amount: 80 } ]
Advertisements