【问题标题】:How to sort an array by timestamp?如何按时间戳对数组进行排序?
【发布时间】:2020-01-01 21:12:06
【问题描述】:

我正在尝试按时间戳值对 array 进行排序。我想按升序对它们进行排序,如果它们中的任何一个具有不确定的属性,请将其放在最后。我目前遇到错误无法读取未定义的属性“first_release_date”。如何解决?

var array = 
[
  {
    "id": 1969,
    "cover": {
      "id": 1960,
      "url": "image.jpg"
    },
    "first_release_date": 1083542400,
    "name": "Item 1"
  },
  {
    "id": 113242,
    "name": "Item 2"
  },
  {
    "id": 25076,
    "first_release_date": 1540512000,
    "name": "Item 3"
  },
  {
    "id": 1969,
    "cover": {
      "id": 1960,
      "url": "image.jpg"
    },
    "name": "Item 4"
  },
  {
    "id": 9245,
    "first_release_date": 1292976000,
    "name": "Item 5"
  }
];

Object.keys(array).forEach((key) => {
  console.log(`Before: ${array[key].name}`)
});

array.sort((a,b) => a.array.first_release_date > b.array.first_release_date);

Object.keys(array).forEach((key) => {
  console.log(`After: ${array[key].name}`)
});

【问题讨论】:

标签: javascript jquery arrays sorting ecmascript-6


【解决方案1】:

你快到了。只需要在没有日期时提供默认值。此外,排序要求您返回一个数字,此时您返回一个布尔值,该布尔值将被强制转换为 0 或 1。这将破坏您想要返回负数的情况的排序。

var array = 
[
  {
    "id": 1969,
    "cover": {
      "id": 1960,
      "url": "image.jpg"
    },
    "first_release_date": 1083542400,
    "name": "Item 1"
  },
  {
    "id": 113242,
    "name": "Item 2"
  },
  {
    "id": 25076,
    "first_release_date": 1540512000,
    "name": "Item 3"
  },
  {
    "id": 1969,
    "cover": {
      "id": 1960,
      "url": "image.jpg"
    },
    "name": "Item 4"
  },
  {
    "id": 9245,
    "first_release_date": 1292976000,
    "name": "Item 5"
  }
];

Object.values(array).forEach((val) => {
  var d = new Date(val.first_release_date*1000).getFullYear();
  console.log(`Before: ${ val.name} ${d }`)
});

array.sort((a,b) => ( a.first_release_date || Number.POSITIVE_INFINITY ) - ( b.first_release_date || Number.POSITIVE_INFINITY ));

Object.values(array).forEach((val) => {
  var d = new Date(val.first_release_date*1000).getFullYear();
  console.log(`After: ${ val.name} ${d }`)
});

var reverse = JSON.parse( JSON.stringify( array ));

reverse.sort((a,b) => ( b.first_release_date || Number.NEGATIVE_INFINITY ) - ( a.first_release_date || Number.NEGATIVE_INFINITY ));

console.log( reverse );

【讨论】:

  • 太棒了。非常感谢。
  • 只是一个问题,如果我想按以下顺序对它们进行排序:2018, 2010, 2004, NaN, NaN。我该怎么做?我更新了您的答案以仅显示年份。问候。
  • 使用相反的:( b.first_release_date || Number.NEGATIVE_INFINITY ) - ( a.first_release_date || Number.NEGATIVE_INFINITY ) 所以b - a 代替a - b,然后NEGATIVE_INFINITY 代替POSITIVE_INFINITY。如果NaNs 不存在,则仅使用Array.reverse() 也可以,但这会将NaNs 放在前面。
  • 哇,谢谢楼主。我去infinity看看。
  • 当您需要一个始终大于/小于数据中某个数字的数字时(例如您需要排序时),就可以使用它。如果我们只使用 -1、0 或 1,那么 NaNs 将首先出现在数组中。因此需要无穷大,这在这种情况下基本上意味着:如果没有日期时间,则始终将项目放置在另一个之后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 2019-03-21
相关资源
最近更新 更多