- 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
Sort array based on presence of fields in objects JavaScript
Let’s say we have the following array of objects −
const people = [{ firstName: 'Ram', id: 301 }, { firstName: 'Shyam', lastName: 'Singh', id: 1016 }, { firstName: 'Dinesh', lastName: 'Lamba', id: 231 }, { id: 341 }, { firstName: 'Karan', lastName: 'Malhotra', id: 441 }, { id: 8881 }, { firstName: 'Vivek', id: 301 }];
We are required to sort this array so that the object with both firstName and lastName property appears first then the objects with firstName or lastName and lastly the objects with neither firstName nor lastName.
So, the code for this will be −
Example
const people = [{ firstName: 'Ram', id: 301 }, { firstName: 'Shyam', lastName: 'Singh', id: 1016 }, { firstName: 'Dinesh', lastName: 'Lamba', id: 231 }, { id: 341 }, { firstName: 'Karan', lastName: 'Malhotra', id: 441 }, { id: 8881 }, { firstName: 'Vivek', id: 301 }]; const sorter = (a, b) => { if(a.firstName && a.lastName){ return -1; }else if(b.firstName || b.lastName){ return 1; }else{ return -1; }; }; people.sort(sorter); console.log(people);
Output
The output in the console will be −
[ { firstName: 'Karan', lastName: 'Malhotra', id: 441 }, { firstName: 'Dinesh', lastName: 'Lamba', id: 231 }, { firstName: 'Shyam', lastName: 'Singh', id: 1016 }, { firstName: 'Ram', id: 301 }, { firstName: 'Vivek', id: 301 }, { id: 8881 }, { id: 341 } ]
Advertisements
To Continue Learning Please Login
Login with Google