Lo-Dash sortBy array of dates in string format

前端 未结 2 2339
说谎
说谎 2021-02-20 00:07

I\'d like to know why lodash doesn\'t sort array of dates in string format as compared with plain javascript sort(). Is it expected behavior or a bug?



        
相关标签:
2条回答
  • 2021-02-20 00:32

    If you are trying to use lodash to sort dates in ascending or descending order for your array of objects, you should use _.orderBy instead of _.sortBy

    https://lodash.com/docs/4.17.15#orderBy, this method allows specifying sort orders either by 'asc' or'desc'

    An example would be:

    const sortedArray = _(myArray.orderBy([
      function(object) {
        return new Date(object.date);
      }],["desc"])
    
    0 讨论(0)
  • 2021-02-20 00:37

    If you take a look to lodash code you may see how it's implemented. Function _.sortBy inside uses native Array.prototype.sort (see source). But the root is not there. More interesting is function compareAscending that is passed as a callback to native sort (source). So in a few words your

    _.sortBy(array, function(value) {return new Date(value);});

    is converted to:

    array.sort(function(a, b) {
        var aa = new Date(a),
            bb = new Date(b);
    
        if (aa !== bb) {
            if (aa > bb) { return 1; }
            if (aa < bb) { return -1; }
        }
        return aa - bb;
    })
    

    So why nulls are in the beginning? Because new Date(null) returns Thu Jan 01 1970 01:00:00 which is less than any other date in your array.

    What about native sort? According to spec (see here) The default sort order is according to string Unicode code points. If simply - native sort converts items to strings and compares strings. So native sort is smth like:

    _.sortBy(array, function(value) {return value + ''; });
    

    As soon as 'null' string is always "bigger" than date string (like '2014-11-11') - nulls will be in the tail of the result array.

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