use Lodash to sort array of object by value

JavascriptArraysSortingLodash

Javascript Problem Overview


I am trying to sort an array by 'name' value (using Lodash). I used the Lodash docs to create the solution below however .orderBy doesn't seem to be having any affect at all. Can anyone shed some light on the correct way to sort array?

Chars Array

[     {        "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"   }]

Function Code

 var chars = this.state.characters;

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

 this.setState({characters: chars})

Javascript Solutions


Solution 1 - Javascript

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})

Solution 2 - Javascript

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)

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser4831663View Question on Stackoverflow
Solution 1 - JavascriptArtémis YoungView Answer on Stackoverflow
Solution 2 - JavascriptCaio SantosView Answer on Stackoverflow
Solution 3 - JavascriptDamian PavlicaView Answer on Stackoverflow