skip to Main Content

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


  1. You are trying to access day property from the elements in dayList which really does not exists and returns undefined.
    You should compare day names directly.

    Change:

    return map[a.day] - map[b.day];
    

    To:

    return map[a] - map[b];
    

    Code Example:

    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] - map[b];
    });
    
    console.log(dayList);
    Login or Signup to reply.
  2. 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.

     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] - map[b]; // Compare directly 
                               using day names
         });
    
     console.log(dayList);
    

    let me know if this can help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search