0

I want to sort an array of days, I found using a pre-defined array reference is better than the JS Date class method.

My array on which sort is called upon doesn't get sorted, even if I always return 1 in the callback, the array never changes.

const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

const toSort = ["monday", "tuesday", "thursday", "friday", "wednesday"];

toSort.sort((a, b) => {
  a = days.indexOf(a);
  b = days.indexOf(b);

  return a < b ? 0 : 1;

  // No matter what I return, the source array remains unchanged
  return a < b ? 1 : 0;
  return 1;
});

console.log(toSort);

Something so out of order (haha get it) from using a basic JS function must mean the answer is stupidly obvious, but I can't figure it out.

  • The snippet sorts the array as expected -> [mcve] – Andreas Jan 04 '23 at 08:05
  • @Andreas No it does not – Guillaume Brunerie Jan 04 '23 at 08:49
  • Just to generalize your issue, `sort` expects the callback to return a "tri-state", that is either negative, zero or positive integer. The tri-state reflects the three possible results of the comparison: smaller than (negative), equal (zero) or greater than (positive). – Teemu Jan 04 '23 at 09:13

2 Answers2

2

Try this:

const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
const toSort = ["monday", "tuesday", "thursday", "friday", "wednesday"];    

toSort.sort(function(a, b){  
  return days.indexOf(a) - days.indexOf(b);
});

console.log(toSort);
riorudo
  • 977
  • 7
  • 14
1

Returning 0 means that the items are equal in terms for order

const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

const toSort = ["monday", "tuesday", "thursday", "friday", "wednesday"];

toSort.sort((a, b) => {
  a = days.indexOf(a);
  b = days.indexOf(b);

  return a === b ? 0 : a > b ? 1 : -1
});

console.log(toSort);
Konrad
  • 21,590
  • 4
  • 28
  • 64