Sort array by date gives unexpected results

前端 未结 2 1829
野的像风
野的像风 2020-12-05 22:52

This will sound as an easy problem but I spent my Sunday trying to figure out what\'s wrong with my implementation described below so I am posting it to SO as a last resort.

相关标签:
2条回答
  • 2020-12-05 23:16

    short answer

    You should return the difference between the two dates, not a boolean:

    // sort the data by date using moment.js
    seriesRawDataArray.sort(function (left, right) {
        return moment.utc(left.timeStamp).diff(moment.utc(right.timeStamp))
    });
    

    why

    Array.prototype.sort expects a negative, zero, or positive value to be returned. Generally, you'll write a sort function like this:

    yourArray.sort(function (a, b) {
        if (a < b) {            // a comes first
            return -1
        } else if (b < a) {     // b comes first
            return 1
        } else {                // equal, so order is irrelevant
            return 0            // note: sort is not necessarily stable in JS
        }
    })
    

    The anonymous function passed to sort serves as the comparator for the native implementation of the sort function.

    However, your negative value doesn't have to be -1 and your positive value doesn't have to be +1. Therefore, when sorting numbers, you can instead use the shortcut:

    yourArray.sort(function (a, b) {
        return a - b
    })
    

    In JavaScript, subtracting two dates coerces them both into numbers, which is why we could use return moment.utc(left.timeStamp).diff(moment.utc(right.timeStamp))

    (instead of direct subtraction -, this method uses moment.prototype.diff from the moment.js library)

    However, in your code, you returned diff > 0, which can be either true or false. Because of type coercion, JavScript will read true as 1 and false as 0. This means your sort function will never return -1. Therefore, your elements will not be sorted correctly.

    0 讨论(0)
  • 2020-12-05 23:26
    let sortedDates = dates.sort(function(a, b){
      return moment(b).format('X')-moment(a).format('X')
    });
    

    Since moment can format valid dates the best way is to use the sort method javascript, so when formatting the date to timestamp, basically you sort by number.

    References:

    http://www.momentjs.com/docs/#/displaying/format

    http://www.w3schools.com/jsref/jsref_sort.asp

    0 讨论(0)
提交回复
热议问题