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

如何在JavaScript中按颜色对对象数组进行排序?

正确实现按颜色名称排序的方法

你的代码问题在于Array.sort()的比较函数使用不正确。sort()要求比较函数接收两个参数(待比较的两个元素a和b),并且返回一个数值:

  • 返回负数:a排在b前面
  • 返回正数:b排在a前面
  • 返回0:两者位置不变

你当前只传入单个参数并返回字符串,这种情况下浏览器会把字符串转为NaN,导致排序逻辑失效,结果是随机的。

方法1:手动实现字符串比较逻辑

手动比较两个颜色名称的字母顺序,同时转为小写避免大小写影响排序结果:

const colors = [
  { "color": "purple", "type": true },
  { "color": "red", "type": false },
  { "color": "green", "type": true },
  { "color": "black", "type": false },
  { "color": "pink", "type": true }
];

const sortedList = colors.sort((a, b) => {
  const colorA = a.color.toLowerCase();
  const colorB = b.color.toLowerCase();
  if (colorA < colorB) return -1;
  if (colorA > colorB) return 1;
  return 0;
});

console.log(sortedList);
// 输出顺序:black, green, pink, purple, red

方法2:使用localeCompare简化代码

String.localeCompare()可以直接返回符合排序要求的数值,还能更好地处理多语言字符的排序场景:

const sortedList = colors.sort((a, b) => a.color.localeCompare(b.color));

如果需要忽略大小写,结合toLowerCase()即可:

const sortedList = colors.sort((a, b) => 
  a.color.toLowerCase().localeCompare(b.color.toLowerCase())
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:00:28