Home > Blockchain >  sort javascript array in custom way - A..a, B..b, ... , Z..z using lodash
sort javascript array in custom way - A..a, B..b, ... , Z..z using lodash

Time:12-11

i am trying to use lodash for sorting array in project. i was checking documentation and i found this ->

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'Fred',   'age': 40 },
  { 'user': 'Barney', 'age': 34 }
];
 
_.sortBy(users, 'user');

when i run this code the output i get is->

0: Object {user: "Barney", age: 34}
1: Object {user: "Fred", age: 40}
2: Object {user: "barney", age: 36}
3: Object {user: "fred", age: 48}

But what i want is this ->

0: Object {user: "Barney", age: 34}
1: Object {user: "barney", age: 36}
2: Object {user: "Fred", age: 40}
3: Object {user: "fred", age: 48}

the sorting order should be something like this ->

A..a,  B..b,  .....  Z..z

Can someone help me here? or is there any other way to do it?

CodePudding user response:

One option is to use vanilla JS by using Intl.Collator and .sort(). You can specify an option of caseFirst as "upper" to sort uppercase letters first:

const users = [ { 'user': 'fred',   'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'Fred',   'age': 40 }, { 'user': 'Barney', 'age': 34 } ];

const collator = new Intl.Collator(undefined, {caseFirst: 'upper'});
const res = users.sort((a, b) => collator.compare(a.user, b.user))
console.log(res);

The same can be achieved with .localeCompare(), but using Intl.Collator can help with performance for larger arrays:

const users = [ { 'user': 'fred',   'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'Fred',   'age': 40 }, { 'user': 'Barney', 'age': 34 } ];

const res = users.sort((a, b) => a.user.localeCompare(b.user, undefined, {caseFirst: "upper"}));
console.log(res);

CodePudding user response:

You can do it in this way :

_.sortBy(users, [function(o) { return o.user.toLowerCase(); },'age']);

simply in first index change user's name to lowercase and in second set age to sorted by age

  • Related