2

maybe someone could explain me how to sort an array of Week Days from Monday...

export const WeekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

WeekDays.sort(
  (a, b) =>
  WeekDays.indexOf(a) - WeekDays.indexOf(b)
);

But the Result is: Wednesday, Monday, Tuesday, Friday, Wednesday... Hope some one can help.

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
tripleD
  • 43
  • 9

2 Answers2

2

The problem is that sort() performs in-place sorting, rather than returning a new sorted array, so your reference array is being sorted. Try sorting a separate array:

const WeekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

const daysToBeSorted = WeekDays.slice();

daysToBeSorted.sort(
  (a, b) =>
  WeekDays.indexOf(a) - WeekDays.indexOf(b)
);

That said, this approach is finding the index of the day (indexOf()) on every iteration of the sort, which in general is not efficient. You could use a Map or an object for fast access of the day's index.

Samuel Olekšák
  • 389
  • 4
  • 12
Berthur
  • 4,300
  • 2
  • 14
  • 28
1

As a supplement to @Berthurs answer here's how you could improve the time complexity of the key function. Its currently O(n) i.e. scales linearly with size of the input.

To reduce that down to constant time O(1) use an object to map the day names to indices in the original array. That way you don't have to look them up again in every call to the key function. They are already computed. If that's not 100% clear orderMap ends up looking like this.

{ "Sunday": 0, "Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4, "Friday": 5, "Saturday": 6 }

The code

const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const orderMap = weekDays.reduce((accum, val, i) => { accum[val] = i; return accum; }, {});

const arrCopy = [...weekDays, ...weekDays, ...weekDays];

arrCopy.sort((a, b) => orderMap[a] - orderMap[b]);
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61