Underscore.js不区分大小写的排序 [英] Underscore.js Case Insensitive Sorting

查看:196
本文介绍了Underscore.js不区分大小写的排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试获取underscore.js进行不区分大小写的排序时存在一些小问题.我有一个对象数组,希望能够按属性名称排序.

Having some slight issues trying to get underscore.js to do case-insensitive sorting. I have an array of objects and would like to be able to sort by property name.

使用快捷方式 sortBy

iteratee也可以是要按其排序的属性的字符串名称(例如,长度).

iteratee may also be the string name of the property to sort by (eg. length).

要排序的数组:

var array = [{ name: 'test_1234', description: 'zzaaa bb cc'}, 
         { name: 'zz1111', description: 'ZAAbbbcc'}, 
         { name: 'TEST', description: '4422'}, 
         { name: '1a2929', description: 'abcdef'}, 
         { name: 'abc', description: 'Full description'}, 
         { name: 'GGGGH', description: '123456'}];

使用此方法进行排序,sortProperty ='name',结果将大写字母放在小写字母之前.

Sorting using this method, sortProperty = 'name', the result places uppercase before lowercase.

var sorted = _.sortBy(array, sortProperty);

1a2929 - abcdef
GGGGH - 123456
TEST - 4422
abc - Full description
test_1234 - zzaaa bb cc
zz1111 - ZAAbbbcc

我认为这与区分大小写有关,但是我无法弄清楚如何将数组中的名称更改为小写并进行比较.

I assume this has to do with case sensitivity, but I can't figure out how to change names in the array to lowercase and compare that way.

非常感谢您的帮助.

如前所述,您传入名称或函数,因此只需调整函数即可返回要排序的字段: http://jsfiddle.net/rjaqp1vg/5/

As pointed out, you pass in name or a function, so just adjusted function to return which field to sort by: http://jsfiddle.net/rjaqp1vg/5/

推荐答案

要排序的名称可以是字段名称或一个函数,因此请传递一个进行小写转换的函数.

The name to sort by can be the field name OR a function, so pass a function that does a lower-case conversion.

var sorted = _.sortBy(array, function (i) { return i.name.toLowerCase(); });

应该可以解决问题.

这篇关于Underscore.js不区分大小写的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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