首页 > 解决方案 > 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

如何正确排序?

标签: javascriptarrayssortingindexing

解决方案


arr.sort((a, b) => a.BustType.localeCompare(b.BustType) || a.index - b.index);

哪个将排序BustType,如果返回0(意味着它们具有相同的BusType),那么右侧将||启动并a.index - b.index使用哪个将排序index。这称为短路评估


推荐阅读