代码之家  ›  专栏  ›  技术社区  ›  Naomi

javascript不区分大小写数组的通用排序

  •  0
  • Naomi  · 技术社区  · 8 年前

    我读过关于这个话题的前一个问题: Lodash : how to do a case insensitive sorting on a collection using orderBy?

    我发现lodash对数值列和日期列进行了正确的排序。我需要对字符串列进行不区分大小写的排序。我们目前有以下实施:

    const sorted = _.orderBy(this, function (o)  {
                if ($.isNumeric(o[column])) {
                    return parseFloat(o[column]);
                }
    
                return (o[column]).toLowerCase();
            }, direction);
            
            this.clear();
        
            for (let i = 0; i < sorted.length; i++) {
                this.push(sorted[i]);
            }

    我担心的是实现不能正确处理日期。我们这里约会需要什么特别的东西吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   ic3b3rg    8 年前

    _.sortBy 可以对日期排序-假设列中的所有值都是日期,则只需测试类型并返回日期:

    const sorted = _.orderBy(this, function(o) {
      if ($.isNumeric(o[column])) {
        return parseFloat(o[column]);
      }
    
      if (_.isDate(o[column])) {
        return o[column];
      }
    
      return (o[column]).toLowerCase();
    }, direction);