4

我有一个像这样创建的动态数组:

window.IDarray = [];

我有一个这样创建的字典:

window.itemdictionary = {};

的长度window.IDarray与 相同window.itemdictionary。的价值window.IDarray是独一无二的。的值window.IDarray也是 的键window.itemdictionary

任何键的“值”的数据类型window.itemdictionary也是一个字典,其中包含一个名为的键"modified",值是格式示例的字符串日期"Mon May 28 11:20:46 EDT 2012"

对 的值进行排序的最佳方法是什么window.IDarray,以便从索引0到末尾window.IDarray,其对应的日期window.itemdictionary离当前日期越来越远?(即 index0将给出最接近当前日期的日期,而 indexn将给出最远的日期)。

4

3 回答 3

3

您将需要使用自定义排序功能,请参阅MDN 中的 Array.sort

首先,为了按日期排序,您"modified": "Mon May 28 11:20:46 EDT 2012"需要转换为可用于比较的格式,使用Date.parse().

var tempItemDictionary = [];   // use temp array to hold the timestamp
// convert dates first
for (var i = 0, item = null; i < IDarray.length; i++) {
    item = itemDictionary[IDarray[i]];
    tempItemDictionary[IDarray[i]] = {
        timestamp: Date.parse(item.modified)    // convert date to timestamp
    };
}

然后我们IDarray使用.sort()自定义排序功能运行:

IDarray.sort(function(a, b) {
    return tempItemDictionary[b].timestamp - tempItemDictionary[a].timestamp;
});

请参阅工作示例:http: //jsfiddle.net/788bs/1/

于 2013-05-29T19:48:46.687 回答
1

使用自定义比较器函数参数对数组进行排序,例如:

IDarray.sort(function(a, b) {
    var date_a, date_b;
    try {
        date_a = Date.parse(itemdictionary[a]['modified'];
        date_b = Date.parse(itemdictionary[b]['modified'];
        return date_a - date_b;
    } catch (e) {
        /* Some smart exception handling for malformed strings? */
    }
});
于 2013-05-29T19:36:13.447 回答
0
window.IDarray = [];
window.itemdictionary = {
    "key0": { modified: "Mon May 28 11:20:46 EDT 2012" },
    "key1": { modified: "Mon May 28 11:20:46 EDT 2012" },
    "key2": { modified: "Mon Sep 20 20:35:15 EDT 2010" },
    "key3": { modified: "Mon May 10 10:07:16 EDT 2010" },
    "key4": { modified: "Tue May 10 10:07:16 EDT 2011" }
};

var sortByDate = function(key1, key2) {
    var date1 = new Date(window.itemdictionary[key1].modified.toString());
    var date2 = new Date(window.itemdictionary[key2].modified.toString());
    return date2 - date1;
};
// lt IE9
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0)
          from += len;

        for (; from < len; from++) {
          if (from in this && this[from] === elt)
            return from;
        }
        return -1;
    };
}

window.itemdictionary.currDate = { modified: new Date().toString() };
window.IDarray = Object.keys(window.itemdictionary);
console.log('before', window.IDarray);
window.IDarray.sort(sortByDate);

delete window.itemdictionary.currDate;
window.IDarray.splice(window.IDarray.indexOf('currDate'), 1);
console.log('after', window.IDarray);

http://jsfiddle.net/nYWmZ/1/

于 2013-05-29T21:01:18.733 回答