Search code examples
javascriptarrayssortinglodash

Use _sortBy of lodash to sort an array by a different field


Having an array of objects like this:

myArray = [
            {AType: "aaa", Description: "De", …},
            {AType: "bbb", Description: "Hi", …},
            {AType: "ccc", Description: "Un", …},
            {AType: "ddd", Description: "Hw", …}, 
            ];

it is sorted by AType but I want to sort it by Description.

I tried to use sortBy from lodash:

import _sortBy from 'lodash/sortBy';

mySortedArray = _sortBy(myArray, s => s.Description);

It doesn't do what I would expect, the result looks like : [Array(4), Array(3), {…}, {…}]

Any ideas how to sort it by that field but also not to modify anything else inside the array?


Solution

  • Not sure what the issue is on your end. Also for a simple sort like this you don't need an arrow function, just the property name.

    myArray = [
        {AType: "aaa", Description: "De"},
        {AType: "bbb", Description: "Hi"},
        {AType: "ccc", Description: "Un"},
        {AType: "ddd", Description: "Hw"}
    ];
    
    mySortedArray = _.sortBy(myArray, 'Description');
    
    console.log(mySortedArray);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>