0

I have the following array

"data":{
  "date_entered":"2021-02-18",
  "order":"1",
},
"data":{
  "date_entered":"2021-02-22",
  "order":"2",
},
"data":{
  "date_entered":"2021-02-15",
  "order":"",
},
"data":{
  "date_entered":"2021-02-18",
  "order":"",
},

I need to sort it so that it first sorts it by order value if that is null then sort by date_entered

so it would sort it by order 1-2 and then date_entered 18th and then 15th

This is is my attempt so far but its far from complete and not sure where to go about this

       if (a.data.order === b.data.order) {
            return 0;
        }

        else if (a.data.order === null) {
            return 1;
        } else if (b.data.order === null) {
            return -1;
        }

        
        return a < b ? 1 : -1;
        

Would greatly appreciate any help

amature
  • 1
  • 1
  • 2
    Your shared input data looks wrong, can you please share the correct input data. – Hassan Imam Feb 19 '21 at 11:35
  • My input data is array of objects, its in json format – amature Feb 19 '21 at 11:38
  • Then please show a _proper_ example of that. So far, you have not done that. What you have shown, does not make sense actually. – CBroe Feb 19 '21 at 11:39
  • Note that `"" === null` is false. If your values are as shown and you want to sort *numerically* (perhaps `order` should be a number to start with?) all you need in a `sort` callback is `return +a.data.order - b.data.order;` if you're okay with treating `""` as though it were `0`, otherwise [my answer here](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875) provides other string-to-number options. If you want to sort *lexicographically* (loosely, alphabetically), then `return a.data.order.localeCompare(b.data.order);` – T.J. Crowder Feb 19 '21 at 11:41
  • @T.J.Crowder thanks for the input but what in the case if i want to first sort by the order value and then sort by the date_entered? – amature Feb 19 '21 at 12:07
  • @amature - See: https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields – T.J. Crowder Feb 19 '21 at 12:13
  • Change `=== null` to `=== ""` – Barmar Feb 19 '21 at 17:42

0 Answers0