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

最有效的方法是什么?


当前回答

你可以创建一个闭包并这样传递它 这是我的例子

$.get('https://data.seattle.gov/resource/3k2p-39jp.json?$limit=10&$where=within_circle(incident_location, 47.594972, -122.331518, 1609.34)', 
  function(responce) {

    var filter = 'event_clearance_group', //sort by key group name
    data = responce; 

    var compare = function (filter) {
        return function (a,b) {
            var a = a[filter],
                b = b[filter];

            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        };
    };

    filter = compare(filter); //set filter

    console.log(data.sort(filter));
});

其他回答

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。

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

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

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()对数组进行排序 克隆数组使用展开运算符(…)使函数纯 按所需键排序(updated_at) 将日期字符串转换为日期对象 Array.sort()的工作原理是,如果current项和next项是一个可以执行无节奏操作的数字/对象,则从current项和next项中减去两个属性

const input = [
  {
    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 sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));

const output = sortByUpdatedAt(input);

console.log(input);
/*
[ { 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' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/

在ES2015支持下,可以通过以下方式完成:

foo.sort((a, b) => a.updated_at < b.updated_at ? -1 : 1)

你可以使用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