除了 Lodash 的 _.sortBy()
方法,还可以使用以下几种方式实现对对象数组按属性值长度排序:
_.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']);
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;
});
_.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]);
方法 | 特点 | 适用场景 |
---|---|---|
_.sortBy() | 简洁,默认升序 | 简单排序需求 |
_.orderBy() | 支持多字段排序和方向指定 | 需明确排序方向时 |
Array.sort() | 原生方法,无需依赖 | 不想引入 Lodash 时 |
_.sortWith() | 支持复杂比较逻辑 | 多条件组合排序 |
实际开发中可根据项目是否已引入 Lodash 以及排序复杂度选择合适的方法。如果已使用 Lodash,_.orderBy()
是兼顾灵活性和简洁性的优选;若追求轻量无依赖,则原生 Array.sort()
更合适。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。