Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...