0

I am new to JS and trying to sort an array based on a key of the object (each object is an element in the array). I am not sure why the following code does not sort the array properly. I have checked the doc carefully and the code looks correct to me. I tried to replace the date value with numerical numbers and it worked. Not sure what is wrong with the date string.

var dic=[{key: '2022-05-13'}, {key: '2022-05-06'}]
dic.sort(function (a, b) {
  return (a.key - b.key);
})
console.log(dic)

Output

[{key: '2022-05-13'}, {key: '2022-05-06'}]

I thought the output should be

[ {key: '2022-05-06'}, {key: '2022-05-13'}]
David
  • 208,112
  • 36
  • 198
  • 279
  • 2
    In Javascript, subtractions will try to convert strings to numbers, and result in `NaN` if it can't be properly represented as a number. Evaluating `'2022-05-13' - '2022-05-06'` gives you `NaN`, which means it does not work in sorting. But given that your date format is 'YYYY-MM-DD', those can be sorted as strings: `dic.sort(function(a, b) { if (a.key < b.key) return -1; if (a.key > b.key) return 1; return 0; })` – qrsngky Jul 16 '22 at 13:23
  • The binary (two operand) `-` operator isn't defined for strings, so your `-` operation converts its operands to numbers using implicit conversion. Those strings don't implicitly convert, so the operation ends up being `NaN - NaN` which is `NaN`, which isn't a value the `sort` method expects from its callback. To compare strings, use `return a.localeCompare(b);` Your format of date strings sorts correctly when you're using string sorting, because you have year, then month, then day. Alternatively, convert the strings... – T.J. Crowder Jul 16 '22 at 13:24
  • ...to dates explicitly and then use `-` (which works with dates, because they convert to number -- the number of milliseconds since Jan 1 1970 at midnight UTC). – T.J. Crowder Jul 16 '22 at 13:24

0 Answers0