如何在纯 JS 中按特定字段(如 _.sortBy)对对象进行排序?

How do I sort objects by a certain field (like _.sortBy) in plain JS?

我正在尝试根据数组对象中的一个 属性 start 对数组进行排序。

events = _.sortBy(events, function(a) {
    return moment(new Date(a.start)).format();
});

这给了我正确的结果。但是,以下没有。

events = events.sort(function(a, b) {
    return moment(new Date(a.start)).format() > moment(new Date(b.start)).format();
});

有人知道发生了什么事吗?

Fiddle: https://jsfiddle.net/q24zx11h/1/

the docs of Array.sort 是这么说的:

arr.sort([compareFunction])

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

你的函数 returns 一个布尔值,然后转换为 Number,即 01,在本例中为 0表示相等(如 "these elements are the same, put them in whatever order")。

比较函数通常return一个整数参数,表示以下值:

  • -1:a小于b
  • 0:a 等于 b
  • 1:a大于b

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

一个方便的技巧是从 b 的离散值中减去 a 的离散值,例如在您的情况下使用时间戳:

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

如果 b 现在大于 a,它将 return 为正值,依此类推。

比较函数必须 return -1、0 或 1:

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

目前您的代码 return 是布尔值,我认为它被解析为 0 或 1,因此您的代码运行但不正确。

我发现你的两个代码的结果相同

    var manualSort = days.sort(function(a, b) {
        return moment(new Date(a.start)).format() > moment(new Date(b.start)).format();
    });

    var underScoreSort = _.sortBy(days, function(a) {
        return moment(new Date(a.start)).format();
    });

两个数组返回相同的结果。