![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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 objects according to days name JavaScript
Let’s say, we have an array of objects that contains data about the humidity over the seven days of a week. The data, however, sits randomly in the array right now. We are supposed to sort the array of objects according to the days like data for Monday comes first, then Tuesday, Wednesday and lastly Sunday.
Following is our array −
const weather = [{ day: 'Wednesday', humidity: 60 }, { day: 'Saturday', humidity: 50 }, { day: 'Thursday', humidity: 65 }, { day: 'Monday', humidity: 40 }, { day: 'Sunday', humidity: 35 }, { day: 'Friday', humidity: 80 }, { day: 'Tuesday', humidity: 45 }];
The key to this problem is creating our map object that maps the specific days of the week to their correct indices. It would look something like this −
const map = { 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7 };
Now with this clear, we can apply the Array.prototype.sort() method passing in a custom callback that ranks the object according to their index in map.
The full code for this will be −
Example
const weather = [{ day: 'Wednesday', humidity: 60 }, { day: 'Saturday', humidity: 50 }, { day: 'Thursday', humidity: 65 }, { day: 'Monday', humidity: 40 }, { day: 'Sunday', humidity: 35 }, { day: 'Friday', humidity: 80 }, { day: 'Tuesday', humidity: 45 }]; const map = { 'Monday': 1,'Tuesday': 2,'Wednesday': 3,'Thursday': 4,'Friday': 5,'Saturday': 6, 'Sunday': 7 }; weather.sort((a, b) => { return map[a.day] - map[b.day]; }); console.log(weather);
Output
The output for this code will be −
[ { day: 'Monday', humidity: 40 }, { day: 'Tuesday', humidity: 45 }, { day: 'Wednesday', humidity: 60 }, { day: 'Thursday', humidity: 65 }, { day: 'Friday', humidity: 80 }, { day: 'Saturday', humidity: 50 }, { day: 'Sunday', humidity: 35 } ]
Advertisements