要使用 Lodash 对数组进行排序,使 value
字符串越短的元素排在越前面,可以使用 _.sortBy()
方法,并传入一个排序函数来比较 value
的长度。
具体实现如下:
const _ = require('lodash');
// 示例数组
const arr = [
{ id: 1, value: 'apple' }, // 长度 5
{ id: 2, value: 'banana' }, // 长度 6
{ id: 3, value: 'cat' }, // 长度 3
{ id: 4, value: 'dog' }, // 长度 3
{ id: 5, value: 'elephant' } // 长度 8
];
// 排序:value 字符串越短,排在越前面
const sortedArr = _.sortBy(arr, item => item.value.length);
console.log(sortedArr);
排序后结果:
[
{ id: 3, value: 'cat' },
{ id: 4, value: 'dog' },
{ id: 1, value: 'apple' },
{ id: 2, value: 'banana' },
{ id: 5, value: 'elephant' }
]
_.sortBy()
会按照传入的迭代函数(这里是 item => item.value.length
)的返回值进行升序排序value
长度相同时(如 'cat' 和 'dog'),将保持它们在原数组中的相对顺序item => -item.value.length
这种方法简洁高效,充分利用了 Lodash 提供的排序功能来实现按字符串长度排序的需求。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。