Lo-Dash sortBy以字符串格式的日期数组 [英] Lo-Dash sortBy array of dates in string format

查看:48
本文介绍了Lo-Dash sortBy以字符串格式的日期数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么lodash与纯JavaScript sort()相比,不对字符串数组中的日期进行排序.是预期的行为还是错误?

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]

使用的版本:Lo-Dash v2.4.1 –现代版本.

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

推荐答案

如果看看lodash代码,您可能会看到它是如何实现的.内部的函数_.sortBy使用本机Array.prototype.sort(请参见).但是根不存在.更有趣的是将函数compareAscending作为回调传递给本机sort(

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);});

转换为:

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;
})

那么为什么null是开头呢?因为new Date(null)返回的Thu Jan 01 1970 01:00:00小于数组中的其他任何日期.

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.

原生sort呢?根据规范(请参见此处) 默认的排序顺序是根据字符串Unicode代码点确定的.如果简单-本机sort会将项目转换为字符串并比较字符串.因此,本机排序就像:

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 + ''; });

一旦'null'字符串总是比日期字符串更大"(例如'2014-11-11')-null将位于结果数组的末尾.

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.

这篇关于Lo-Dash sortBy以字符串格式的日期数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆