Javascript Lodash:如何使用 orderBy 对集合进行不区分大小写的排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37848030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash : how to do a case insensitive sorting on a collection using orderBy?
提问by WhiteEleven
I checked this answerbut to achieve the same result, that is to get case-insensitive sorting, I need to use orderBy
instead of sortBy
since it gives the ability to specify the sort order.
我检查了这个答案,但为了获得相同的结果,即获得不区分大小写的排序,我需要使用orderBy
而不是sortBy
因为它提供了指定排序顺序的能力。
The only way I found to achieve it was to create a cloned "middle" array mapped to lower case the name
:
我发现实现它的唯一方法是创建一个映射到小写的克隆“中间”数组name
:
const users = [
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'b', age: 40 },
{ name: 'a', age: 36 }
];
let lowerCaseUsers = _.clone(users);
lowerCaseUsers = lowerCaseUsers.map((user) => {
user.name = user.name.toLowerCase();
return user;
});
const sortedUsers = _.orderBy(lowerCaseUsers, ['name'], ['desc']);
console.log(sortedUsers);
This seems really expensive and it will even be more complex with multiple sortings and dynamic properties names.
这看起来真的很昂贵,而且如果有多个排序和动态属性名称,它甚至会更加复杂。
Is there a better idea ?
有更好的主意吗?
Here is a Plunker : https://plnkr.co/edit/i1ywyxjFctuNfHtPTcgG
这是一个 Plunker:https://plnkr.co/edit/i1ywyxjFctuNfHtPTcgG
回答by Felix Kling
The documentationspecifies that you can pass a function as "iteratee":
该文档指定您可以将函数作为“iteratee”传递:
[iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]): The iteratees to sort by.
[iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]):要排序的迭代对象。
So you can do
所以你可以做
const users = [
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'b', age: 40 },
{ name: 'a', age: 36 }
];
const sortedUsers = _.orderBy(users, [user => user.name.toLowerCase()], ['desc']);
console.log(sortedUsers);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
回答by MaxineHu
Ordering by multiple properties:
按多个属性排序:
const users = [
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'b', age: 40 },
{ name: 'a', age: 36 }
]
const nameSorter = user => user.name.toLowerCase()
const ageSorter = 'age'
const sortedUsers = _.orderBy(users, [nameSorter, ageSorter], ['desc', 'asc'])
回答by Agustí Sánchez
You can combine Felix Kling example with _.get function to sort by dynamic nested attributes:
您可以将 Felix Kling 示例与 _.get 函数结合使用,以按动态嵌套属性进行排序:
const _ = require('lodash');
let test = [{ a: {b:'AA'}},{a: {b:'BB'} }, {a: {b: 'bb'}}, {a:{b:'aa'}}];
let attrPath = 'a.b';
_.orderBy(test, [item => _.get(item, attrPath).toLowerCase()]);