Actionscript: Sorting ArrayCollection by date: YYYY-MM-DD

不羁岁月 提交于 2020-01-14 05:44:09

问题


I have an ArrayCollection of Objects. Each Object has the following keys/values:

{date: 2009-12-01, visits=13555, bouceRate=45}
{date: 2009-12-05, visits=46955, bouceRate=45}
{date: 2009-12-06, visits=13685, bouceRate=45}
{date: 2009-12-02, visits=13685, bouceRate=45}
{date: 2009-12-04, visits=68755, bouceRate=45}
{date: 2009-12-03, visits=35875, bouceRate=45}

I need to sort this ArrayCollection by date, so it would be from past to present - like so:

{date: 2009-12-01, visits=13555, bouceRate=45}
{date: 2009-12-02, visits=13685, bouceRate=45}
{date: 2009-12-03, visits=35875, bouceRate=45}
{date: 2009-12-04, visits=68755, bouceRate=45}
{date: 2009-12-05, visits=46955, bouceRate=45}
{date: 2009-12-06, visits=13685, bouceRate=45}

I have tried the following with no prevail (not sorting):

var dateSort:Sort = new Sort();
    dateSort.fields = [new SortField("date", false, false, true)];

newAreaChartData.sort = dateSort;
newAreaChartData.refresh();

// traceout
for (var i:int = 0; i <newAreaChartData.length; i++)
    trace ("Object #" + i + ": " + ObjectUtil.toString(newAreaChartData.getItemAt(i)));

回答1:


This worked for me:

for(i = 0; i < newAreaChartData.length; ++i) {
    newAreaChartData[i].formattedDate = getActualDate(newAreaChartData[i].date);
    newAreaChartData[i].dateTime =    newAreaChartData[i].formattedDate.time;
    trace(newAreaChartData[i].dateTime);
}

    var dateSort:Sort = new Sort();
    dateSort.fields = [new SortField("dateTime", false, false, true)];
    newAreaChartData.sort = dateSort; 
    newAreaChartData.refresh();

for (var i:int = 0; i <newAreaChartData.length; i++)
    trace ("Object #"+ i + ": " + ObjectUtil.toString(newAreaChartData.getItemAt(i)));



回答2:


The way your creating the SortField :

new SortField("date", false, false, true)

From the API , the last parameter should mean that you want the value to be sorted numerically instead of as a string.

What is the type of the "date" field in the Object ? If it is a string, then you might want to sort things alphabetically

new SortField("date", false, false, null)

Hoping this helps

PH




回答3:


I don't believe that the sort is applied until you call ArrayCollection.refresh():

newAreaChartData.sort = dateSort;
newAreaChartData.refresh();


来源:https://stackoverflow.com/questions/1868197/actionscript-sorting-arraycollection-by-date-yyyy-mm-dd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!