0

I have an array of arrays that I need to sort, but I'm having trouble getting it figured out. My main array (mainArr) looks like this:

mainArr = ({code:"1", date:"1/2/2001", status:"Active"},
           {code:"2", date:"6/2/2004", status:"Terminated"},
           {code:"3", date:"2/2/2003", status:"Transferred"},
           {code:"4", date:"9/2/2003", status:"Active"});

I need to sort the mainArr by the dates in the objects. The list should end up like this:

mainArr = ({code:"1", date:"1/2/2001", status:"Active"},
           {code:"3", date:"2/2/2003", status:"Transferred"},
           {code:"4", date:"9/2/2003", status:"Active"}.
           {code:"2", date:"6/2/2004", status:"Terminated"});
Adrian
  • 42,911
  • 6
  • 107
  • 99
mkyong
  • 12,497
  • 12
  • 37
  • 56

1 Answers1

0

In most cases, you can use the sortOn method of Array. For instance, if you wanted to sort by 'code':

mainArr.sortOn("code");

This will sort the array using the code field of each object to determine the order.

However, as you wish to sort by dates (in a string format), sorting will give incorrect results (as ordering alphabetically and in date order are not the same). You could add a new property to each object in the array to make sorting easier, eg:

{code:"1", date:"1/2/2001", status:"Active"}

Adding the date in reverse order (sortableDate), it would become:

{code:"1", date:"1/2/2001", status:"Active", sortableDate:"2001/2/1"}

and you can then order with:

mainArr.sortOn("sortableDate");