我有一个具有几个键值对的对象数组,我需要根据'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"
    }
]

最有效的方法是什么?


当前回答

使用下划线js或lodash,

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

arrObj = _.sortBy(arrObj,"updated_at");

_.sortBy()返回一个新数组

请参阅http://underscorejs.org/#sortBy和 lodash docs https://lodash.com/docs#sortBy

其他回答

我在这里已经回答了一个非常类似的问题:对对象数组进行排序的简单函数

对于这个问题,我创建了一个小函数,可以做你想做的事情:

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

array. sort()方法对数组中的元素进行排序并返回数组。小心使用Array.sort(),因为它不是不可变的。对于不可变排序使用immutable-sort。

This method is to sort the array using your current updated_at in ISO format. We use new Data(iso_string).getTime() to convert ISO time to Unix timestamp. A Unix timestamp is a number that we can do simple math on. We subtract the first and second timestamp the result is; if the first timestamp is bigger than the second the return number will be positive. If the second number is bigger than the first the return value will be negative. If the two are the same the return will be zero. This alines perfectly with the required return values for the inline function.

For ES6:

arr.sort((a,b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());

一对ES5的:

arr.sort(function(a,b){ 
 return new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime();
});

如果你把updated_at改为unix时间戳,你可以这样做:

For ES6:

arr.sort((a,b) => a.updated_at - b.updated_at);

一对ES5的:

arr.sort(function(a,b){ 
 return a.updated_at - b.updated_at;
});

在撰写本文时,现代浏览器还不支持ES6。要在现代浏览器中使用ES6,请使用babel将代码转译为ES5。期待在不久的将来浏览器对ES6的支持。

Array.sort()应该接收三种可能结果之一的返回值:

正数(第一项>第二项) 负数(第一项<第二项) 如果两项相等,则为0

注意,内联函数的返回值可以是任何值 正数或负数。Array.Sort()并不关心 返回编号为。它只关心返回值是否为正, 负或者零。

对于不可变排序:(ES6中的例子)

const sort = require('immutable-sort');
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

你也可以这样写:

import sort from 'immutable-sort';
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

import-from是在ES6中包含javascript的一种新方法,它使你的代码看起来非常干净。我个人的最爱。

不可变排序不会改变源数组,而是返回一个新数组。建议在不可变数据上使用const。

为了完整起见,这里有一个sortBy的简短泛型实现:

function sortBy(list, keyFunc) {
  return list.sort((a,b) => keyFunc(a) - keyFunc(b));
}

sortBy([{"key": 2}, {"key": 1}], o => o["key"])

注意,这里使用了就地排序的数组排序方法。 对于副本,您可以使用arr.concat()或arr.slice(0)或类似的方法来创建副本。

你可以使用Lodash实用程序库来解决这个问题(它是一个非常有效的库):

Const data = [{ “updated_at”:“2012 - 01 - 01 t06:25:24z”, “foo”:“酒吧” }, { “updated_at”:“2012 - 01 - 09年t11:25:13z”, “foo”:“酒吧” }, { “updated_at”:“2012 - 01 - 05 t04:13:24z”, “foo”:“酒吧” } ] const ordered = _.orderBy( 数据, 函数(项){ 返回item.updated_at; } ); console.log(命令) < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js " > < /脚本>

你可以在这里找到文档:https://lodash.com/docs/4.17.15#orderBy

我说得有点晚了,但在2021年,正确的答案是使用inter . collator。updated_at是一个ISO-8601字符串,因此可以作为字符串进行排序。转换为Date是一种浪费时间的操作,如果手动比较返回0、1或-1也是如此。

const 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"
  }
];

const { compare } = Intl.Collator('en-US');
arr.sort((a, b) => compare(a.updated_at, b.updated_at));

Intl。Collator返回一个函数,可以用作#Array.sort的compareFunction。因为我们在对一个对象排序,所以我们调用compare函数与我们要排序的键的值进行比较。

注意,如果我们对一个字符串数组排序,我们可以简单地这样做:

arr.sort(compare);

还要注意,正如其他人指出的那样,sort会使原始数组发生变异。如果这是不可取的,您可能希望首先克隆它。在2021年,你可以这样做:

[...arr].sort((a, b) => compare(a.updated_at, b.updated_at));