I’m going to sort day name based on array list day with below code:
var dayList = ['Mon', 'Fri', 'Sun', 'Wed', 'Sat'];
const map = {
'Mon': 1,'Tue': 2,'Wed': 3,'Thu': 4,'Fri': 5,'Sat': 6, 'Sun': 7
};
dayList.sort((a, b) => {
return map[a.day] - map[b.day];
});
console.log(dayList);
But it show me same sort result to :
[ "Mon", "Fri", "Sun", "Wed", "Sat"]
It should be like this:
[ "Mon", "Wed", "Fri", "Sat", "Sun"]
Any idea how to make it work?
2
Answers
You are trying to access day property from the elements in
dayList
which really does not exists and returnsundefined
.You should compare day names directly.
Change:
To:
Code Example:
It looks like there’s a small issue in your sorting function. The day property is not necessary since you’re directly comparing the day names from the dayList array.
let me know if this can help you.