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

发布于 2024-12-12 05:21:37 字数 499 浏览 0 评论 0原文

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

[
  { 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" }
]

How would you sort this array with these objects by distance, so that you have the objects sorted from smallest distance to biggest distance?

[
  { 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" }
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

再浓的妆也掩不了殇 2024-12-19 05:21:37

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

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

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

它通过返回一个整数来实现这一点

  • 负数(小于零):第一个参数排在前面
  • 正数(大于零):第二个参数排在前面
  • 参数被视为相等

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

Use Array.prototype.sort(), eg

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

The sort() method accepts a comparator function. This function accepts two arguments (both presumably of the same type) and it's job is to determine which of the two comes first.

It does this by returning an integer

  • Negative (less-than zero): The first argument comes first
  • Positive (greater-than zero): The second argument comes first
  • Zero: The arguments are considered equal for sorting

When you're dealing with numeric values, the simplest solution is to subtract the second value from the first which will produce an ascending order result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文