首页 > 解决方案 > 如何使用字典对数组进行排序?[Javascript]

问题描述

假设我有这个数组:

[
  {num: 0, otherdatas: 'blah'},
  {num: 5, otherdatas: 'blah'},
  {num: 3, otherdatas: 'blah'},
  {num: 8, otherdatas: 'blah'},
  {num: 9, otherdatas: 'blah'},
  {num: 4, otherdatas: 'blah'}
]

我想对这个数组进行排序。像这样:

[
  {num: 0, otherdatas: 'blah'},
  {num: 3, otherdatas: 'blah'},
  {num: 4, otherdatas: 'blah'},
  {num: 5, otherdatas: 'blah'},
  {num: 8, otherdatas: 'blah'},
  {num: 9, otherdatas: 'blah'}
]

如果数组是这样[0, 5, 3, 8, 9, 4]的,排序会很容易,但我在字典上有这些数字。我可以为这个数组做什么?

标签: javascriptarraysdictionary

解决方案


Array.prototype.sort接受一个名为 的可选参数compareFunction,它是一个定义排序顺序的函数。

它应该接受 2 个参数,a 和 b,要比较的 2 个元素,并返回一个数字,如果小于 0,则表示 a < b,如果大于 0,则表示 a > b,如果为 0,则表示 a = b。

你可以在 MDN 上找到它。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


推荐阅读