- 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
Sorting an associative array in ascending order - JavaScript
Suppose, we have an array of objects like this −
const people = [ {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"}, {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"}, {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"}, {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"} ];
We are required to write a JavaScript function that takes in one such array and sorts the array in place, according to the age property of each object in increasing order.
Therefore, the output should look something like this −
const output = [ {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"}, {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"}, {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}, {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"} ];
Example
Following is the complete code −
const people = [ {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"}, {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"}, {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"}, {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"} ]; const sorter = (a, b) => { return a.age - b.age; }; const sortByAge = arr => { arr.sort(sorter); }; sortByAge(people); console.log(people);
Output
This will produce the following output in console −
[ { id: 3, name: 'Christine', age: 20, gender: 'm', category: 'G' }, { id: 2, name: 'Brandon', age: 25, gender: 'm', category: 'G' }, { id: 4, name: 'Elena', age: 29, gender: 'W', category: 'M' }, { id: 1, name: 'Andrew', age: 30, gender: 'm', category: 'G' } ]
Advertisements