

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 }
- Related Questions & Answers
- How to Sort object of objects by its key value JavaScript
- How to sort an ArrayList in Java in ascending order?
- How to sort an ArrayList in Ascending Order in Java
- Python program to sort the elements of an array in ascending order
- C program to sort an array in an ascending order
- JavaScript - Sort key value pair object based on value?
- How to perform ascending order sort in MongoDB?
- 8086 program to sort an integer array in ascending order
- Java Program to Sort Array list in an Ascending Order
- C program to sort an array of ten elements in an ascending order
- How to sort by value with MySQL ORDER BY?
- How do you sort an array in C# in ascending order?
- How to sort Java array elements in ascending order?
- How to access an object value using variable key in JavaScript?
- JavaScript: How to Create an Object from Key-Value Pairs
Advertisements