javascript - 如何使用字典对数组进行排序?[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]
的,排序会很容易,但我在字典上有这些数字。我可以为这个数组做什么?
解决方案
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
推荐阅读
- database - Flutter - Sembast 数据库插入对象列表
- java - 我不明白“count++”的功能
- node.js - Nodejs 承诺子解决父承诺
- ios - NSMutableData 从 Objective-C 中的 JSON 响应中获取键值
- node.js - 强制 selenium-webdriver 绑定到 localhost
- c++ - 如何使我的 for 循环转到 char* 数组的末尾并将每个城市放在链表中(城市被空格分隔)
- windows - 可以通过 ClickOnce 部署窗口的控制台应用程序吗?
- local-storage - 如何从离子4,角度7中的本地存储中删除具有特定键的数组中的元素
- java - 似乎无法让我的 Java 在 VS Code 中工作
- javascript - 如何选择仅具有特定属性的元素?