我想用lodash排序一个对象数组
要使用Lodash实现对象数组按integrals字段的特殊排序逻辑(A > B > A,B),可按以下步骤操作:
解决方案代码
const _ = require('lodash');
function sortIntegrals(arr) {
return _.sortBy(arr, (item) => {
const integrals = item.integrals;
const hasA = integrals.includes('A');
const hasB = integrals.includes('B');
// 优先级规则:A(0) < B(1) < A,B(2)
if (hasA && !hasB) return 0;
if (!hasA && hasB) return 1;
return 2; // 同时包含A和B的情况
});
}
// 示例用法
const data = [
{ integrals: ['B'] },
{ integrals: ['A'] },
{ integrals: ['A', 'B'] },
{ integrals: ['B'] },
{ integrals: ['A'] }
];
const sortedData = sortIntegrals(data);
console.log(sortedData);
关键逻辑说明
- 优先级映射规则:
- 仅含
A→ 优先级0(最高) - 仅含
B→ 优先级1 - 同时含
A,B→ 优先级2(最低)
- Lodash实现:
- 使用
_.sortBy()进行稳定排序 - 通过
Array.includes()检测元素存在性 - 逻辑判断顺序确保
A优先于B,混合情况最后
执行结果示例
输入数组排序后将变为:
[
{ integrals: ['A'] },
{ integrals: ['A'] },
{ integrals: ['B'] },
{ integrals: ['B'] },
{ integrals: ['A', 'B'] }
]
此方案严格遵循用户指定的排序规则,且时间复杂度为O(n log n),适合大多数实际场景。
posted on 2025-10-06 23:54 fox_charon 阅读(20) 评论(0) 收藏 举报
浙公网安备 33010602011771号