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

如何用Lodash及原生JavaScript对数组中名称按字母排序?

嘿,我看到你在尝试用Lodash给对象数组按name字段排序时踩了个小坑——问题出在你把_.sortBy()的用法和原生Array.sort()搞混啦!Array.sort()需要传入比较函数,但Lodash的_.sortBy()本身就会返回一个排好序的新数组,不需要再嵌套传给sample.sort()。咱们来一步步修正:

一、正确的Lodash实现

首先,_.sortBy()的正确姿势是直接传入目标数组和排序用的迭代器函数,它会返回全新的已排序数组(不会修改原数组)。如果要做忽略大小写的排序,只需要在迭代器里把name转成统一的大写(或小写)即可:

// 确保已经引入Lodash(比如通过npm安装后导入)
const _ = require('lodash');

const sample = [
  { name: "AddMain", mesg: "test000" },
  { name: "Ballside", mesg: "test004545" },
  { name: "TestMain", mesg: "test00" },
  { name: "ball", mesg: "test004545" },
  { name: "Main", mesg: "test004545" },
  { name: "alliswell", mesg: "test004545" }
];

// 忽略大小写按name升序排序
const sortedArray = _.sortBy(sample, item => item.name.toUpperCase());

console.log(sortedArray);
// 输出顺序:alliswell, AddMain, ball, Ballside, Main, TestMain

如果需要降序排序,可以用更灵活的_.orderBy(),它支持指定排序方向:

// 忽略大小写按name降序排序
const sortedDescArray = _.orderBy(sample, [item => item.name.toUpperCase()], ['desc']);
二、原生JavaScript实现

要是不想依赖Lodash,原生Array.sort()也能完美实现同样的效果,核心是写一个自定义比较函数,把两个对象的name转成统一大小写后再比较:

const sample = [/* 你的原始数组 */];

// 忽略大小写升序排序(会修改原数组)
sample.sort((a, b) => {
  const normalizedA = a.name.toUpperCase();
  const normalizedB = b.name.toUpperCase();
  if (normalizedA < normalizedB) return -1;
  if (normalizedA > normalizedB) return 1;
  return 0;
});

// 不想修改原数组?先复制一份再排序:
const sortedSample = [...sample].sort((a, b) => {
  const normalizedA = a.name.toUpperCase();
  const normalizedB = b.name.toUpperCase();
  return normalizedA.localeCompare(normalizedB); // 用localeCompare更简洁
});

// 降序的话,把localeCompare的结果取反即可:
const sortedDescSample = [...sample].sort((a, b) => {
  const normalizedA = a.name.toUpperCase();
  const normalizedB = b.name.toUpperCase();
  return -normalizedA.localeCompare(normalizedB);
});

为啥你的原代码失效?

你之前写的sample.sort(sortBy('name', false, function(a){return a.toUpperCase()})),错误在于_.sortBy()返回的是一个数组,而sample.sort()需要的是比较函数(一个返回数字的函数),所以自然无法正常工作啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:43:49