javascript sort placing middle item at top

I have the following sort function:

var timeArray = new Array('11:41', '11.39', '11:41', '11:41', '11:40', '11:70', '11:39', '11:38', '11:38', '11:37', '11:37');

timeArray.sort(function(c, d) {
        var digit1 = parseInt(c.replace(/\D/g,''));
        var digit2 = parseInt(d.replace(/\D/g,''));
        return  digit1 > digit2;});

var testContent = '';
for (var i = 0; i < timeArray.length; i++) {
    testContent += timeArray[i] + '<br />';
}

$('#test').html(testContent);

Where I would expect to see the following result:

11:37
11:37
11:38
11:38
11.39
11:39
11:40
11:41
11:41
11:41
11:70

However, the 11.70 number always appears at the top of the results. If I change the 11:70 value in the array, no matter what value I use that is the one that will always appear at the start of the results.

Does anyone know how I can sort this properly and why the 11:70 always appears at the top of the list?

Example Fiddle

Answers:

Answer

Change the sort function to

timeArray.sort(function(c, d) {
    var digit1 = parseInt(c.replace(/\D/g,''));
    var digit2 = parseInt(d.replace(/\D/g,''));
    return  digit1 - digit2;
});

FIDDLE

It's expecting a number to be returned, not a boolean.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.