除了 Lodash 的 _.sortBy()
方法,还可以使用以下几种方式实现对对象数组按属性值长度排序:
1. Lodash 的 _.orderBy()
方法
_.orderBy()
比 _.sortBy()
更灵活,支持指定排序方向(升序/降序):
const _ = require('lodash');
const items = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cat' }
];
// 按 name 长度升序(短->长)
const sortedAsc = _.orderBy(items, [item => item.name.length], ['asc']);
// 按 name 长度降序(长->短)
const sortedDesc = _.orderBy(items, [item => item.name.length], ['desc']);
2. 原生 JavaScript 的 Array.sort()
方法
不依赖 Lodash 时,可直接使用数组原生的 sort()
方法:
const items = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cat' }
];
// 升序排序(短->长)
const sortedAsc = [...items].sort((a, b) => {
return a.name.length - b.name.length;
});
// 降序排序(长->短)
const sortedDesc = [...items].sort((a, b) => {
return b.name.length - a.name.length;
});
3. Lodash 的 _.sortWith()
方法(自定义比较器)
对于更复杂的排序逻辑,可以使用 _.sortWith()
配合自定义比较器函数:
const _ = require('lodash');
const items = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cat' }
];
// 按 name 长度升序
const sortedAsc = _.sortWith(items, [(a, b) => a.name.length - b.name.length]);
// 按 name 长度降序
const sortedDesc = _.sortWith(items, [(a, b) => b.name.length - a.name.length]);
各方法对比
方法 | 特点 | 适用场景 |
| 简洁,默认升序 | 简单排序需求 |
| 支持多字段排序和方向指定 | 需明确排序方向时 |
| 原生方法,无需依赖 | 不想引入 Lodash 时 |
| 支持复杂比较逻辑 | 多条件组合排序 |
实际开发中可根据项目是否已引入 Lodash 以及排序复杂度选择合适的方法。如果已使用 Lodash,_.orderBy()
是兼顾灵活性和简洁性的优选;若追求轻量无依赖,则原生 Array.sort()
更合适。