0

I am having an odd problem with an array of dates not being fully sorted. The majority of the array seems to be sorting correctly, however there is an oddity where the first two elements in the array are not being sorted, or are being sorted incorrectly.

Code:

var arrSortTest = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];

for (var i = 0; i < arrSortTest.length; i++) {
  arrSortTest.sort(function(i) {
    var temp = new Date(i);
    return temp
  });
}
console.log(arrSortTest)

What I expected: ["July 11, 1615", "October 18, 1851", "July 11, 1960", "February 1, 1974", "November 12, 1995"]

What I get: ["October 18, 1851", "July 11, 1615", "July 11, 1960", "February 1, 1974", "November 12, 1995"]

The above code seems like it should just work, and it seems like it does for the most part. What should I be doing differently here to get the dates in my test array sorted from oldest to newest? Am I just not understanding how sorting an array with dates even works?

Thank you in advance.

shrys
  • 5,860
  • 2
  • 21
  • 36
Dev-MDW2
  • 113
  • 9
  • See [this](https://stackoverflow.com/questions/10123953/sort-array-by-a-date-property) – Paul Rooney Jul 19 '19 at 03:38
  • Got it. Looks like my question is really just a duplicate. If needed, it can be marked as such. Thanks Paul. – Dev-MDW2 Jul 19 '19 at 03:40
  • The code doesn't make a lot of sense. It's calling sort multiple times, once for each element in the array. You only need to call sort once to sort the entire array. Also, the function passed to sort takes 2 arguments, a and b and returns -1 if the a < b, 0 if a === b, and 1 if a > b but yours just returns a new Date based on `i`. It's not even using any of the values of the array – gman Jul 19 '19 at 03:40
  • @PaulRooney : You can mark this as a duplicate if needed. It looks like my question is. – Dev-MDW2 Jul 19 '19 at 03:42
  • @gman: I know that now. I wasn't really understanding how the sort function was supposed to work until I looked at pindev's code snippet below. I understand it now, and I realize my code is pretty much nonsense. – Dev-MDW2 Jul 19 '19 at 03:43

1 Answers1

5

function handler in sort should have two parameters and return positive number when first element is greater than second one, negative number when first one is smaller than second one, and 0 when they are same.

So the code should be:

var arrSortTest = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];

arrSortTest.sort(function(i, j) {
  return new Date(i).getTime() - new Date(j).getTime();
});

console.log(arrSortTest)
Julian W.
  • 1,501
  • 7
  • 20
  • This works perfectly. Also the explanation makes sense. I guess I just was not understanding the sort function entirely. Thank you @pindev. I appreciate the help. – Dev-MDW2 Jul 19 '19 at 03:39