Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  107] [ 4]  / answers: 1 / hits: 38242  / 10 Years ago, fri, november 14, 2014, 12:00:00

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?



var array = [2014-11-11, 2014-11-12, null, 2014-11-01, null, null, 2014-11-05];

_.sortBy(array);
// [2014-11-11, 2014-11-12, null, 2014-11-01, null, null, 2014-11-05]

_.sortBy(array, function(value) {return new Date(value);});
// [null, null, null, 2014-11-01, 2014-11-05, 2014-11-11, 2014-11-12]

array.sort();
// [2014-11-01, 2014-11-05, 2014-11-11, 2014-11-12, null, null, null]


Version used: Lo-Dash v2.4.1 – Modern build.


More From » sorting

 Answers
11

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.


[#68804] Wednesday, November 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patienceannel

Total Points: 674
Total Questions: 101
Total Answers: 101

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;