You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据数组中对象的数值属性对数组进行数值排序?

嘿,看你给出的数组,应该是想根据对象里的distance属性来排序对吧?这其实很简单,用JavaScript数组的sort()方法就能轻松搞定,我给你一步步讲清楚:

首先先把你的数组整理成标准格式(应该是包裹在数组里的对象集合):

const locations = [
  {opp_id: 123, latitude: "40.0467921", longitude: "-76.29504939999998", distance: 4.326332246421182},
  {opp_id: 115, latitude: "39.9492628", longitude: "-76.69909960000001", distance: 24.81327544469476},
  {opp_id: 66, latitude: "40.0467921", longitude: "-76.29504939999998", distance: 4.326332246421182},
  {opp_id: 64, latitude: "37.7863453", longitude: "-122.44204609999997", distance: 24.12345} // 补全了省略的数值
];

按距离升序排序(从近到远)

如果你想让距离最近的对象排在最前面,用下面的代码:

// 升序排序,原地修改原数组
locations.sort((a, b) => a.distance - b.distance);

// 不想改动原数组的话,先复制一份再排序
const sortedAscending = [...locations].sort((a, b) => a.distance - b.distance);

原理很简单:sort()的比较函数里,a.distance - b.distance如果是负数,就把a放在b前面;正数则反过来,刚好实现从小到大的排序。

按距离降序排序(从远到近)

要是想让最远的排在前面,只需要把减法的顺序反过来:

// 降序排序,原地修改
locations.sort((a, b) => b.distance - a.distance);

// 不改动原数组的版本
const sortedDescending = [...locations].sort((a, b) => b.distance - a.distance);

小提醒

  • sort()默认会原地修改原数组,如果你还需要保留原来的数组顺序,一定要像上面那样用扩展运算符[...locations]先复制一份,或者用Array.from(locations)也行。
  • 你的例子里distance已经是数值类型了,没问题;如果是字符串格式的数字,记得先转成数值再比较,比如parseFloat(a.distance) - parseFloat(b.distance)。

内容的提问来源于stack exchange,提问作者Logan C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:17:49