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

问题描述

我有一个包含多个键值对的对象数组,我需要根据updated_at"对它们进行排序:

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

最有效的方法是什么?

解决方案

您可以使用 Array.sort.

这是一个例子:

var arr = [{"updated_at": "2012-01-01T06:25:24Z","foo": "酒吧"},{"updated_at": "2012-01-09T11:25:13Z","foo": "酒吧"},{"updated_at": "2012-01-05T04:13:24Z","foo": "酒吧"}]arr.sort(function(a, b) {var keyA = new Date(a.updated_at),keyB = 新日期(b.updated_at);//比较两个日期if (keyA < keyB) 返回 -1;如果 (keyA > keyB) 返回 1;返回0;});console.log(arr);

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?

解决方案

You can use Array.sort.

Here's an example:

var arr = [{
    "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"
  }
]

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;
});

console.log(arr);

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

09-09 14:30