Lodash:如何使用orderBy对集合进行不区分大小写的排序? [英] Lodash : how to do a case insensitive sorting on a collection using orderBy?

查看:217
本文介绍了Lodash:如何使用orderBy对集合进行不区分大小写的排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了这个答案,但要达到相同的效果,那就是获取不区分大小写的排序,我需要使用 orderBy 而不是 sortBy ,因为它可以指定排序顺序

I checked this answer but 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.

我发现实现它的唯一方法是创建一个克隆的中间数组,映射到小写 name

The only way I found to achieve it was to create a cloned "middle" array mapped to lower case the 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.

有更好的主意吗?

这是一个Plunker: https://plnkr.co/edit/i1ywyxjFctuNfHtPTcgG

Here is a Plunker : https://plnkr.co/edit/i1ywyxjFctuNfHtPTcgG

推荐答案

文档指定您可以将函数传递为iteratee:

The documentation specifies that you can pass a function as "iteratee":


[iteratees = [_。identity]](Array [] | Function [] | Object [] | string [ ]):迭代次数排序。

[iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]): The iteratees to sort by.

所以你可以做到

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>

这篇关于Lodash:如何使用orderBy对集合进行不区分大小写的排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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