Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use Lodash to sort array of object by value

People also ask

How do you sort an array by object value?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you use sortBy Lodash?

Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee.


This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

Your code could be like:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

If you need to sort by date, you could use this solution:

orderBy(items, (a) => new Date(a.createdAt), ['asc']) // or 'desc'

If you are using moment library, then:

orderBy(items, (a) => moment(a.createdAt), 'asc')

P.s. Note that the lodash doesn't sort dates in string format, so you must convert it to Date object.