- 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
How to sort an object in ascending order by the value of a key in JavaScript?
Suppose we have the following object −
const obj = { "sub1": 56, "sub2": 67, "sub3": 98, "sub4": 54, "sub5": 87 };
We are required to write a JavaScript function that takes in one such object. Then our function should sort the object in ascending order of the values present in the object. And then at last, we should return the object thus formed.
Example
The code for this will be −
const obj = { "sub1": 56, "sub2": 67, "sub3": 98, "sub4": 54, "sub5": 87 }; const sortObject = obj => { const sorter = (a, b) => { return obj[a] - obj[b]; }; const keys = Object.keys(obj); keys.sort(sorter); const res = {}; keys.forEach(key => { res[key] = obj[key]; }); return res; }; console.log(sortObject(obj));
Output
And the output in the console will be −
{ sub4: 54, sub1: 56, sub2: 67, sub5: 87, sub3: 98 }
Advertisements