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

最有效的方法是什么?


当前回答

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

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

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

其他回答

这是一个稍微修改过的@David Brainer-Bankers的答案,按字母顺序排序,或按数字排序,并确保以大写字母开头的单词不会排在以小写字母开头的单词之上(例如“apple,Early”将按此顺序显示)。

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];

        if (typeof x == "string")
        {
            x = (""+x).toLowerCase(); 
        }
        if (typeof y == "string")
        {
            y = (""+y).toLowerCase();
        }

        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

为了完整起见,这里有一个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)或类似的方法来创建副本。

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

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

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。

arr.sort(函数(a,b){返回新的日期(a.updated_at) -新的日期(b.updated_at)})

Arr = [ { "updated_at": "2012-01-01 t6:25:24 z ", "foo": "bar" }, { "updated_at": "2012-01-09T11:25:13Z", "foo": "bar" }, { "updated_at": "2012-01-05T04:13:24Z", "foo": "bar" } ]; arr.sort(函数(a,b){返回新的日期(a.updated_at) -新的日期(b.updated_at)}); console.log (arr);

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。