javascript - JS按两个值排序
问题描述
我需要带有 Bustype 和索引的排序数组
我有的
[
{ BusType: "SATA", index: 1, Id: "SATA.1" },
{ BusType: "SATA", index: 10, Id: "SATA.10" },
{ BusType: "IDE", index: 1, Id: "IDE.1" },
{ BusType: "IDE", index: 2, Id: "IDE.2" },
{ BusType: "IDE", index: 10, Id: "IDE.10" },
]
预期输出:
[
{ BusType: "IDE", index: 1, Id: "IDE.1" },
{ BusType: "IDE", index: 2, Id: "IDE.2" },
{ BusType: "IDE", index: 10, Id: "IDE.10" },
{ BusType: "SATA", index: 1, Id: "SATA.1" },
{ BusType: "SATA", index: 10, Id: "SATA.10" }
]
我试过这个:
arr.sort((a, b) => a.Id.localeCompare(b.Id))
但得到了这个:
[
{ BusType: "IDE", index: 1, Id: "IDE.1" },
{ BusType: "IDE", index: 10, Id: "IDE.10" },
{ BusType: "IDE", index: 2, Id: "IDE.2" },
{ BusType: "SATA", index: 1, Id: "SATA.1" },
{ BusType: "SATA", index: 10, Id: "SATA.10" }
]
像字母一样排序.. 1 10 100 2 20 3
如何正确排序?
解决方案
arr.sort((a, b) => a.BustType.localeCompare(b.BustType) || a.index - b.index);
哪个将排序BustType
,如果返回0
(意味着它们具有相同的BusType
),那么右侧将||
启动并a.index - b.index
使用哪个将排序index
。这称为短路评估。
推荐阅读
- shopify - 如何将自定义 html 块添加到页脚选项列表中?
- python - 删除从 API python 中提取的部分引用
- php - 如何在 Laravel 路由页面中使用会话数据(auth)
- mockito - 使用 mockito-inline 库对本地创建的对象进行模拟方法调用
- flutter - 方法 2 不填充名字
- quadratic-programming - 在 docplex 中添加二次约束
- azure-aks - 未启动运行状况检查的 Azure Kubernetes 服务 pod 超时且没有错误日志
- angular - 为什么 Jasmine 会抛出很多错误:无法在测试模块已经实例化时配置测试模块?
- matlab - 去除具有多个连续值的异常值,类似于一个步骤
- php - 错误:购物车项目总金额与订单金额不匹配