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.

5
  • See this Commented Jul 19, 2019 at 3:38
  • Got it. Looks like my question is really just a duplicate. If needed, it can be marked as such. Thanks Paul. Commented Jul 19, 2019 at 3: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 Commented Jul 19, 2019 at 3:40
  • @PaulRooney : You can mark this as a duplicate if needed. It looks like my question is. Commented Jul 19, 2019 at 3: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. Commented Jul 19, 2019 at 3:43

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.