javascript - 如何正确使用字段对数组进行排序

标签 javascript arrays sorting

我有一个数组,我想用数组中的字段进行排序,但它不起作用

var data = [{tm: "09:00", tr: "30.34", rd: "73.23"},
{tm: "09:10", tr: "30.45", rd: "70.77"},
{tm: "09:50", tr: "29.95", rd: "75.70"},
{tm: "09:40", tr: "29.95", rd: "75.70"},
{tm: "01:50", tr: "29.95", rd: "75.70"},
{tm: "02:30", tr: "29.95", rd: "75.70"},
{tm: "04:50", tr: "29.95", rd: "75.70"},
{tm: "10:00", tr: "30.05", rd: "76.20"}];

我需要使用 tm 字段对其进行排序,以便排序后数据将采用这种格式

0 tm: 01.50
1 tm: 02.30
2 tm: 04.50
3 tm: 09.00
4 tm: 09.10
5 tm: 09.40
6 tm: 09.50
7 tm: 10.00

我试过了

data.sort(function(a, b){return a.tm - b.tm});

它不起作用任何帮助将不胜感激谢谢

最佳答案

HH:MM 本质上是可排序的,因此传递给 localeCompare 将按预期工作。

var data = [{tm: "09:00", tr: "30.34", rd: "73.23"},
{tm: "09:10", tr: "30.45", rd: "70.77"},
{tm: "09:50", tr: "29.95", rd: "75.70"},
{tm: "09:40", tr: "29.95", rd: "75.70"},
{tm: "01:50", tr: "29.95", rd: "75.70"},
{tm: "02:30", tr: "29.95", rd: "75.70"},
{tm: "04:50", tr: "29.95", rd: "75.70"},
{tm: "10:00", tr: "30.05", rd: "76.20"}];

data.sort((a, b) => a.tm.localeCompare(b.tm));

console.log(data)

关于javascript - 如何正确使用字段对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55812270/

相关文章:

arrays - 具有线性进展的动态数组的摊销复杂性?

javascript - 按值对数据集数组排序[1]

python - 是否有返回排序列表的 list.sort() 版本?

java - 如何对字符串数组进行排序和过滤?

javascript - VueJS 中的下拉菜单(事件菜单的切换)

javascript - 使用 lodash _.sortby 对包含详细信息的联系人数组进行排序并最后发送空值?

javascript - MongoDB 从聚合中排除某些文档

JavaScript : send actual html code to url

ruby - 要散列的散列数组

C++ 使用带字符串数组的 execvp