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

JavaScript中如何仅按字符串首字符对数组进行排序?

基于字符串首字符排序并保留原顺序的实现方法

要实现仅按字符串索引0处的字符排序,同时保留原数组中首字符相同元素的相对顺序,只需给sort()传入自定义比较函数:

const arr = [ 'a', 'aa', 'aaa' ];
const sortedArr = arr.sort((a, b) => {
  const firstCharA = a[0];
  const firstCharB = b[0];
  // 比较首字符的Unicode编码值
  if (firstCharA < firstCharB) return -1;
  if (firstCharA > firstCharB) return 1;
  // 首字符相同时返回0,维持原数组的相对顺序
  return 0;
});
console.log(sortedArr); // 输出: ['a', 'aa', 'aaa']

原理说明

  • 默认的sort()会将字符串转为Unicode码点序列逐位比较,所以会出现'aaa' > 'aa' > 'a'的结果。
  • 自定义比较函数中,仅对比两个字符串的首字符:
    • 首字符不同时,按Unicode顺序排序;
    • 首字符相同时返回0,现代JavaScript引擎的sort()(符合ES2019标准)是稳定排序,会保留这些元素在原数组中的相对位置,从而让排序后的数组和原数组顺序一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:15:54