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

最有效的方法是什么?


当前回答

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

其他回答

你可以使用array。sort。

这里有一个例子: Var arr = [{ “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”:“酒吧” } ] 加勒比海盗。排序(函数(a, b) { var keyA = new Date(a.updated_at), keyB = new Date(b.updated_at); //比较两个日期 if (keyA < keyB)返回-1; if (keyA > keyB)返回1; 返回0; }); console.log (arr);

这是一个稍微修改过的@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));
    });
}

使用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' } ]
*/

我说得有点晚了,但在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));

这是另一种更数学的方式,做同样的事情,但更短:

arr.sort(function(a, b){
    var diff = new Date(a.updated_at) - new Date(b.updated_at);
    return diff/(Math.abs(diff)||1);
});

或者在光滑的lambda箭头样式中:

arr.sort((a, b) => {
    var diff = new Date(a.updated_at) - new Date(b.updated_at);
    return diff/(Math.abs(diff)||1);
});

这个方法可以使用任何数字输入