2

lodash sortByOrder is not working as expected

Following is a demo code in my angular app. But sortByOrder is not getting imported correctly.

I;ve updated with latest version of lodash. I've also updated @types/lodash.

import { sortByOrder } from 'lodash';

const users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 34 },
  { 'user': 'fred',   'age': 42 },
  { 'user': 'barney', 'age': 36 }
];
 
// sort by `user` in ascending order and by `age` in descending order
_.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

I am getting following error

lodash/ts3.1"' has no exported member 'sortByOrder'.
adiga
  • 34,372
  • 9
  • 61
  • 83
reacg garav
  • 477
  • 1
  • 4
  • 11
  • Lodash has no `sortByOrder` method, only a [`sortBy` one](https://lodash.com/docs#sortBy)? – Bergi Jun 27 '20 at 15:00

2 Answers2

3

Do you really need lodash for it? Look at this example with vanilla js

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

let result = users.sort((a,b) => a.user.localeCompare(b.user) || (b.age - a.age));

console.log(result);

Since version 4 its called _.orderBy

bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • lodash sortbyOrder offers multiple sortby options & also sort direction. Feels like more easy. What happened to this method(sortByOrder)? . If this is impossible is there a way to sort by multiple params like sortByOrder(from lodash) in vanilla js? – reacg garav Jun 27 '20 at 13:06
  • if you take a look: https://stackoverflow.com/questions/22928841/lodash-multi-column-sortby-descending its now `orderBy` since version 4 – bill.gates Jun 27 '20 at 13:08
  • is there a way to do something like this var data = _.orderBy(array_of_objects, ['item.type','item.name'], ['asc', 'desc']); - instead of keys can I have key paths? – reacg garav Jun 27 '20 at 14:40
  • https://stackoverflow.com/questions/62611489/how-to-sort-array-of-objects-with-deep-nested-properties-using-lodash-orderby – reacg garav Jun 27 '20 at 14:48
2

Import Lodash like this

import * as _ from 'lodash';

You can use Lodash _.orderBy function to order using multiple properties

const data = _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
Vinay
  • 2,272
  • 4
  • 19
  • 34