You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript字符串值二维数组的正确排序方法咨询

失效原因

你写的sortArr排序函数使用a[1] - b[1]作为返回值,减号运算符会隐式将两侧的操作数转换为数字后再做计算。
对于arr1的第二项是数字字符串,可以正常转换为数字,减法能返回合法的正负值或者0,因此排序可以正常生效。
对于arr2的第二项是纯字符串,转换为数字会得到NaN,NaN参与减法运算结果还是NaN,Array.sort()接收到NaN返回值时会判定两个元素优先级相等,不会调整元素顺序,因此排序失效。

解决方案

使用字符串原生的localeCompare方法替换减法运算即可实现字符串排序:

const sortArrByStr = (a, b) => a[1].localeCompare(b[1]);
let sortedArr2 = arr2.sort(sortArrByStr);

排序后sortedArr2的结果为:
[['NC', 'North Carolina'], ['PA', 'Pennsylvania'], ['WA', 'Washington']],符合预期排序效果。

进阶用法

localeCompare支持传入参数适配更多排序场景:

  • 忽略大小写排序
    // 大小写不敏感排序,比如Apple和apple会判定为相等
    const caseInsensitiveSort = (a, b) => a[1].localeCompare(b[1], undefined, { sensitivity: 'base' });
    
  • 特定语言排序
    // 中文按拼音首字母排序
    const zhSort = (a, b) => a[1].localeCompare(b[1], 'zh-CN');
    

内容的提问来源于stack exchange,提问作者Vlad Khoroshkov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:39:01