对象的数组排序与日期值单键 [英] Sort array of objects by single key with date value

查看:150
本文介绍了对象的数组排序与日期值单键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个键值对对象的数组,我需要根据的updated_at'对它们进行排序:

I have an array of objects with several key value pairs, and I need to sort them based on 'updated_at':

[
    {
        "updated_at" : "2012-01-01T06:25:24Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-09T11:25:13Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-05T04:13:24Z",
        "foo" : "bar"
    }
]

什么是这样做的最有效的方法是什么?

What's the most efficient way to do so?

推荐答案

您可以使用<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort\"><$c$c>Array.sort.

下面是一个(未经测试)例如:

Here's an (untested) example:

arr.sort(function(a, b){
    var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
    // Compare the 2 dates
    if(keyA < keyB) return -1;
    if(keyA > keyB) return 1;
    return 0;
});

这篇关于对象的数组排序与日期值单键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆