Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash orderby partial sort

I have an array with elements shown below. I need to sort the array partially. Whereas all elements with fix===1 should come first, with the order they appear in the dataset preserved. All others (fix==0) should then follow sorted by jobDueDate.

I have tried the following:

_.orderBy(data, ['fix', 'jobDueDate'], ['desc', 'asc']);

Which will put entries with fix==1 on top but will also apply sorting to them, which is not the requirement.

[
  {
    "id": 6060,
    "jobNumber": 1878,
    "jobDueDate": "2018-02-07T00:00:00",
    "fix": 1
  },
  {
    "id": 5337,
    "jobNumber": 1836,
    "jobDueDate": "2018-02-05T00:00:00",
    "fix": 1
  },
  {
    "id": 5702,
    "jobNumber": 1863,
    "jobDueDate": "2018-02-06T00:00:00",
    "fix": 1
  },
  {
    "id": 32583,
    "jobNumber": 1611,
    "jobDueDate": "1753-01-01T00:00:00",
    "fix": 0
  },
  {
    "id": 33403,
    "jobNumber": 1932,
    "jobDueDate": "2008-01-28T00:00:00",
    "fix": 0
  },
  {
    "id": 29481,
    "jobNumber": 2741,
    "jobDueDate": "2018-02-03T00:00:00",
    "fix": 0
  },
  {
    "id": 278,
    "jobNumber": 1541,
    "jobDueDate": "2018-02-05T00:00:00",
    "fix": 0
  },
  {
    "id": 5331,
    "jobNumber": 1836,
    "jobDueDate": "2018-02-05T00:00:00",
    "fix": 0
  },
  {
    "id": 5708,
    "jobNumber": 1863,
    "jobDueDate": "2018-02-06T00:00:00",
    "fix": 0
  },
  {
    "id": 6066,
    "jobNumber": 1878,
    "jobDueDate": "2018-02-07T00:00:00",
    "fix": 0
  },
  {
    "id": 5193,
    "jobNumber": 1825,
    "jobDueDate": "2018-02-08T00:00:00",
    "fix": 0
  }
]
like image 778
Adnan Ashraf Avatar asked May 03 '26 16:05

Adnan Ashraf


1 Answers

Use a custom sorting function which implements the required logic. If I got you right, this should do the trick for you:

_.sortBy(input, (o) => o.fix == 1 ? 0 : o.jobDueDate);
like image 166
Ente Avatar answered May 06 '26 05:05

Ente



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!