【问题标题】:Javascript sort array of strings by number and then letter [duplicate]Javascript按数字和字母对字符串数组进行排序[重复]
【发布时间】:2021-07-13 22:41:38
【问题描述】:

使用这个对象数组:

[
{a: "1M"},
{a: "10D"},
{a: "1D"},
{a: "6Y"},
{a: "3D"}
]

如何排序这个数组得到这个结果:

[
"1D",
"3D",
"10D",
"1M",
"6Y"
]

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 尝试将每个值拆分为数字和字符串。
  • 我尝试使用 localeCompare,将自定义函数传递给 sort 方法,但没有得到想要的结果
  • 如果先按数字排序,然后按字母排序,您想要的数组不是 1D、1M、3D、6Y、10D 吗?还是我错过了什么?
  • @reastere 建议您在问题中包含您尝试过的内容。

标签: javascript string sorting compare


【解决方案1】:

您可以使用一个对象来获取给定单位的因子并按值排序。

const
    getValue = s => ({ D: 1, M: 30, Y: 365 })[s.slice(-1)] * s.slice(0, -1),
    array = [{ a: "1M" }, { a: "10D" }, { a: "1D" }, { a: "6Y" }, { a: "3D" }],
    result = array
        .map(({ a }) => a)
        .sort((a, b) => getValue(a) - getValue(b));

console.log(result);

按字母排序

const
    array = [{ a: "1M" }, { a: "10D" }, { a: "1D" }, { a: "6Y" }, { a: "3D" }],
    result = array
        .map(({ a }) => a)
        .sort((a, b) =>
            a.slice(-1).localeCompare(b.slice(-1)) ||
            a.slice(0, -1) - b.slice(0, -1)
    );

console.log(result);

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2019-03-16
    • 1970-01-01
    • 2021-03-16
    • 2011-03-10
    相关资源
    最近更新 更多