Lodash : how to do a case insensitive sorting on a collection using orderBy?

[亡魂溺海] 提交于 2019-11-27 13:23:33

问题


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.

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.

Is there a better idea ?


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


回答1:


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

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

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>



回答2:


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'])



回答3:


You can combine Felix Kling example with _.get function to sort by dynamic nested attributes:

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


来源:https://stackoverflow.com/questions/37848030/lodash-how-to-do-a-case-insensitive-sorting-on-a-collection-using-orderby

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