【问题标题】:How to sort an array based on the second value with javascript? [duplicate]如何使用javascript根据第二个值对数组进行排序? [复制]
【发布时间】:2022-02-09 05:11:39
【问题描述】:

我有一个数组:

[
    [0, 'Please select a Customer'],
    [2072, 'S-Customer'],
    [834, '01-Customer'],
    [709, 'C-Customer'],
    [4217, 'Test'],
    [2074, 'A-Customer']
]

但是我怎样才能按数字和字母顺序对其进行排序,并且仍然具有相同的 ID,即第一个值?应该是这样的:

obs:第一个值不应该改变。

[
    [0, 'Please select a Customer'],
    [834, '01-Customer'],
    [2074, 'A-Customer'],
    [709, 'C-Customer'],
    [2072, 'S-Customer'],
    [4217, 'Test']
]

【问题讨论】:

    标签: javascript html css ecmascript-6


    【解决方案1】:

    您可以通过查找索引 0 来保留第一个数组,然后按索引 1 的值对其余数组进行排序

    const
        array = [[0, 'Please select a Customer'], [2072, 'S-Customer'], [834, '01-Customer'], [709, 'C-Customer'], [4217, 'Test'], [2074, 'A-Customer']];
        
    
    array.sort((a, b) => !b[0] - !a[0] || a[1].localeCompare(b[1]));
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2020-01-14
      • 2013-12-16
      • 2014-05-07
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多