我有一个数组的数组,我需要排序,但我有麻烦弄清楚。我的主数组(mainArr)看起来像这样:
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"});
我需要根据对象中的日期对mainArr进行排序。该列表应该像这样结束:
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"});
在大多数情况下,可以使用Array的sortOn方法。例如,如果你想按'code'排序:
mainArr.sortOn("code");
这将使用每个对象的code字段对数组进行排序,以确定顺序。
但是,当您希望按日期(以字符串格式)排序时,排序将给出不正确的结果(因为按字母顺序排序和按日期顺序排序是不一样的)。您可以为数组中的每个对象添加一个新属性以使排序更容易,例如:
{code:"1", date:"1/2/2001", status:"Active"}
按倒序添加日期(sortableDate),它将变成:
{code:"1", date:"1/2/2001", status:"Active", sortableDate:"2001/2/1"}
,然后你可以用:
mainArr.sortOn("sortableDate");