I need help to reorder this array.object

Flavio Tiezzi
Kilo Sage

Hello guys,

I have this array.object and I need to reorder it so that if it has an empty displayOrder it will be last considering the type.

[
  {
    "displayOrder": "",
    "type": "moment",
  },
  {
    "displayOrder": "2",
    "type": "moment",
  },
  {
    "displayOrder": "4",
    "type": "moment",
  },
  {
    "displayOrder": "1",
    "type": "presentation",
  }
]

//Reorder to this:


[

  {
    "displayOrder": "2",
    "type": "moment",
  },
  {
    "displayOrder": "4",
    "type": "moment",
  },
  {
    "displayOrder": "",
    "type": "moment",
  },
  {
    "displayOrder": "1",
    "type": "presentation",
  }
]

 

What could I do to achieve this?

 

Thanks in advance!

2 REPLIES 2

Mohith Devatte
Tera Sage
Tera Sage

Hello @Flavio Tiezzi ,

you can do like below 

var arr=[
  {
    "displayOrder": "",
    "type": "moment",
  },
  {
    "displayOrder": "2",
    "type": "moment",
  },
  {
    "displayOrder": "4",
    "type": "moment",
  },
  {
    "displayOrder": "1",
    "type": "presentation",
  }
];


arr.sort(function(a,b){return a[1] - b[1]});
arr.reverse();
gs.print(JSON.stringify(arr));

Hope this helps 

MARK MY ANSWER CORRECT IF IT HELPS YOU

Nick Parsons
Mega Sage

Use the .sort() method with a custom compare function:

var res = arr.slice().sort(function(a, b) {
    return a.type.localeCompare(b.type) || (a.displayOrder == "") - (b.displayOrder == "") || a.displayOrder - b.displayOrder;
});

gs.info(JSON.stringify(res, null, 2));

First we localeCompare the type to sort lexicographically on the type field. Then we sort by the difference of equating whether displayOrder between two objects is empty (if just one of them is empty we return -1 or 1 to reorder a and b). Lastly, we sort by the delta between the two display order values. 

Result is:

[
  {
    "displayOrder": "2",
    "type": "moment"
  },
  {
    "displayOrder": "4",
    "type": "moment"
  },
  {
    "displayOrder": "",
    "type": "moment"
  },
  {
    "displayOrder": "-1",
    "type": "presentation"
  },
  {
    "displayOrder": "1",
    "type": "presentation"
  }
]

Note: Depending on where this data is coming from, you might be able to sort this data in a different way. Eg: If you're using GlideRecord to get this data, then you should be using .orderBy() in your original query to sort.