|
| 1 | +# Sorting Arrays Of Objects With Lodash |
| 2 | + |
| 3 | +The [`lodash`](https://lodash.com/) library comes with a couple functions for |
| 4 | +sorting collections of objects -- |
| 5 | +[`sortBy`](https://lodash.com/docs/4.17.15#sortBy) and |
| 6 | +[`orderBy`](https://lodash.com/docs/4.17.15#orderBy). |
| 7 | + |
| 8 | +Consider the following collection of pokemon: |
| 9 | + |
| 10 | +```javascript |
| 11 | +const pokemon = [ |
| 12 | + { name: "Pikachu", level: 12 }, |
| 13 | + { name: "Charmander", level: 12 }, |
| 14 | + { name: "Squirtle", level: 15 }, |
| 15 | + { name: "Bulbasaur", level: 11 } |
| 16 | +]; |
| 17 | +``` |
| 18 | + |
| 19 | +This collection can be sorted in ascending order by the value of a key in the |
| 20 | +object using `sortBy`. |
| 21 | + |
| 22 | +```javascript |
| 23 | +import _sortBy from "lodash/sortBy"; |
| 24 | + |
| 25 | +_sortBy(pokemon, ["level"]); |
| 26 | +``` |
| 27 | + |
| 28 | +If you want to control whether the sorting is in ascending or descending order, |
| 29 | +use `orderBy`. |
| 30 | + |
| 31 | +```javascript |
| 32 | +import _orderBy from "lodash/orderBy"; |
| 33 | + |
| 34 | +_orderBy(pokemon, ["level"], ["desc"]); |
| 35 | +``` |
| 36 | + |
| 37 | +You can also do sorting with primary and secondary keys by including two values |
| 38 | +in the key sort array. |
| 39 | + |
| 40 | +```javascript |
| 41 | +import _sortBy from "lodash/sortBy"; |
| 42 | + |
| 43 | +_sortBy(pokemon, ["name", "level"]); |
| 44 | +``` |
| 45 | + |
| 46 | +And if you want to indpendently control ascending/descending for these as well, |
| 47 | +you can. |
| 48 | + |
| 49 | +```javascript |
| 50 | +import _orderBy from "lodash/orderBy"; |
| 51 | + |
| 52 | +_orderBy(pokemon, ["level", "name"], ["desc", "asc"]); |
| 53 | +``` |
| 54 | + |
| 55 | +Check out the [live example](https://codesandbox.io/s/jolly-ardinghelli-cem7t) |
| 56 | +to see it in action. |
0 commit comments