javascript - 按对象属性值对数组进行数字排序

标签 javascript arrays sorting javascript-objects

如何按距离对包含这些对象的数组进行排序,以便将对象从最小距离排序到最大距离?

[
  { distance: 3388, duration: "6 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
  { distance: 13564, duration: "12 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
  { distance: 4046, duration: "6 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
  { distance: 11970, duration: "17 mins", from: "Lenchen Ave, Centurion 0046, South Africa" }
]

最佳答案

使用Array.prototype.sort() , 例如

myArray.sort((a, b) => a.distance - b.distance)

sort() 方法接受一个比较器 函数。这个函数接受两个参数(假设都是同一类型),它的工作是确定两个参数中哪个先出现。

它通过返回一个整数

来做到这一点
  • 负数(小于零):第一个参数在前
  • 正数(大于零):第二个参数在前
  • 零:参数在排序时被认为是相等的

当您处理数值时,最简单的解决方案是从第一个值中减去第二个值,这将产生升序结果。

关于javascript - 按对象属性值对数组进行数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7889006/

相关文章:

通过 Objective-C 消息传递访问 C 风格对象数组的正确语法?

sorting - 是否可以在 Julia 中对字典进行排序?

javascript - 路由链接遵循 URL,而不是由 Angular 路由

javascript - JS : Access from a property to another property in the same object

c++ - for循环和string函数中指针的操作和bool初值

php - 如何在 PHP 准备语句中将数据插入数组?

javascript - 在 React 上设置默认 ref 值?

javascript - 对象.观察顺序

python - 使用 OrderedDict 按项目长度对 python 字典进行排序

c++ - 使用 C++ 在 NxN 数组中查找 M 个最大元素的优化方法