Underscore.js Case Insensitive Sorting

柔情痞子 提交于 2019-11-26 17:22:25

问题


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.

Using shortcut method sortBy

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

Array to be sorted:

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'}];

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.

Any help is greatly appreciated.

Edit: 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/


回答1:


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

should do the trick.




回答2:


Don't use _.sortBy for this. The correct way to sort strings alphabetically is to use localeCompare. Here's an example in pure Javascript:

['Z', 'A','z','á', 'V'].sort(function(a, b){
   return a.localeCompare(b, undefined /* Ignore language */, { sensitivity: 'base' }) 
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare.



来源:https://stackoverflow.com/questions/25873635/underscore-js-case-insensitive-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!