-3

I need this array sorted by key (weekday). Currently it is displayed as sunday - friday

"weekOverview": {
"Sunday": 0.1111111111112,
"Monday": 0.1111111111111,
"Tuesday": 0.1100204936741015,
"Wednesday": 0.8655145400508841,
"Thursday": 0.2206230378805767,
"Friday": 0.7633485206232166,
"Saturday": 1.6047637274510986

},

Yet I need it displayed as monday - sunday

"weekOverview": {
"Monday": 0.1111111111111,
"Tuesday": 0.1100204936741015,
"Wednesday": 0.8655145400508841,
"Thursday": 0.2206230378805767,
"Friday": 0.7633485206232166,
"Saturday": 1.6047637274510986
"Sunday": 0.1111111111112,

},

Thanks in advance!

Wolf
  • 13
  • 4
  • 3
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Dec 07 '21 at 10:43
  • 1
    What's your reason to sort the properties in the object? – evolutionxbox Dec 07 '21 at 10:43
  • This might help: https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key – aerial Dec 07 '21 at 10:45

1 Answers1

0

Here is a sortByDays method which does exactly what you want it to do.

We utilize Object.keys, as well as a custom sorter object.

const weekOverview = {
  Sunday: 0.1111111111112,
  Monday: 0.1111111111111,
  Tuesday: 0.1100204936741015,
  Wednesday: 0.8655145400508841,
  Thursday: 0.2206230378805767,
  Friday: 0.7633485206232166,
  Saturday: 1.6047637274510986,
};

const sortByDays = (obj) => {
  const sorter = {
    Monday: 1,
    Tuesday: 2,
    Wednesday: 3,
    Thursday: 4,
    Friday: 5,
    Saturday: 6,
    Sunday: 7,
  };
  const newMap = {};
  Object.keys(obj)
    .sort((a, b) => {
      return sorter[a] - sorter[b];
    })
    .forEach((item) => {
      newMap[item] = weekOverview[item];
    });
  return newMap;
};

console.log(sortByDays(weekOverview))

Better solution:

const weekOverview = {
    Sunday: 0.1111111111112,
    Monday: 0.1111111111111,
    Tuesday: 0.1100204936741015,
    Wednesday: 0.8655145400508841,
    Thursday: 0.2206230378805767,
    Friday: 0.7633485206232166,
    Saturday: 1.6047637274510986,
};

const sortWeek = (obj) => {
    const week = {
        Monday: null,
        Tuesday: null,
        Wednesday: null,
        Thursday: null,
        Friday: null,
        Saturday: null,
        Sunday: null,
    };

    for (const [key, value] of Object.entries(week)) {
        if (obj[key]) week[key] = obj[key];
    }

    return week;
};

console.log(sortWeek(weekOverview));
mstephen19
  • 1,733
  • 1
  • 5
  • 20