Search code examples
javascriptnode.jslodash

Using lodash nested array of object will be sorted out


I have the below dataset which needs to be sorted based on "AcctCode" and "SuperID" as below expected result using lodash.

Anyone help me how to sort out in Ascending order based on "AcctCode" and "SuperID" as below I have mentioned the expected result set. I have used _.orderBy(data), but it gives an answer for if we pass the whole array of an object not what I have mentioned below.

Example data set:

[
  {
    "100" : [
      {
        "id" : 1,
        "EmpId" : 100,
        "AcctCode" : "2002-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      },
      {
        "id" : 2,
        "EmpId" : 100,
        "AcctCode" : "2001-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      },
      {
        "id" : 3,
        "EmpId" : 100,
        "AcctCode" : "2000-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      }
    ],
   "101" : [
     {
        "id" : 4,
        "EmpId" : 101,
        "AcctCode" : "2001-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      },{
        "id" : 3,
        "EmpId" : 100,
        "AcctCode" : "2001-10",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      } 
    ] 
  }]

Expected result as below

 [
  {
    "100" : [
       {
        "id" : 3,
        "EmpId" : 100,
        "AcctCode" : "2000-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      },
      {
        "id" : 2,
        "EmpId" : 100,
        "AcctCode" : "2001-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      },
      {
        "id" : 1,
        "EmpId" : 100,
        "AcctCode" : "2002-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      },


    ],
   "101" : [
     {
        "id" : 4,
        "EmpId" : 101,
        "AcctCode" : "2001-00",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      },{
        "id" : 3,
        "EmpId" : 100,
        "AcctCode" : "2001-10",
        "SuperID" : 2000,
        "ReportNo" : "10000"
      } 
    ] 
  }]

Solution

  • You need to map the values of data[0] using mapValues and then use orderby:

    const result = _.mapValues(data[0], items => 
        _.orderBy(items, ['AcctCode', 'SuperID'], ['asc', 'desc'] ))
    

    It's not clear what the sort order for SuperID should be, so I've just set it to descending.