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

如何使用Lodash排序函数按重要性级别对对象数组排序?

用Lodash按自定义重要性级别排序任务数组

没问题!要实现按你需要的重要性顺序(critical > important > moderate > unimportant)排序这个任务数组,核心是先给每个重要性等级分配明确的优先级权重,再用Lodash的排序函数基于这个权重排序。

步骤1:定义优先级映射表

先创建一个对象,把每个重要性标签对应到一个数字——数字越小,代表优先级越高:

const priorityMap = {
  critical: 1,
  important: 2,
  moderate: 3,
  unimportant: 4
};

步骤2:用Lodash的排序函数处理数组

Lodash提供了两个常用的排序函数,都能轻松实现需求:

方案1:使用 _.orderBy(更灵活,支持指定排序方向)

_.orderBy可以同时指定多个排序维度和方向,这里我们只需要基于优先级权重升序排列:

var tasks = [ 
  { importance: 'moderate', task: 'do laundry' }, 
  { importance: 'critical', task: 'brush teeth' }, 
  { importance: 'important', task: 'buy milk' }, 
  { importance: 'unimportant', task: 'wash car' }, 
];

const priorityMap = {
  critical: 1,
  important: 2,
  moderate: 3,
  unimportant: 4
};

const sortedTasks = _.orderBy(tasks, [task => priorityMap[task.importance]], ['asc']);

// 输出结果:
// [
//   { importance: 'critical', task: 'brush teeth' },
//   { importance: 'important', task: 'buy milk' },
//   { importance: 'moderate', task: 'do laundry' },
//   { importance: 'unimportant', task: 'wash car' }
// ]

方案2:使用 _.sortBy(更简洁,默认升序)

如果不需要调整排序方向,_.sortBy是更简洁的选择,它默认按升序排列:

const sortedTasks = _.sortBy(tasks, task => priorityMap[task.importance]);

额外处理:兼容未知优先级的情况

如果数组里存在importance字段不在映射表中的任务,可以给这些任务设置一个默认权重,让它们排在最后:

const sortedTasks = _.sortBy(tasks, task => priorityMap[task.importance] || 5);
// 这里用5作为默认值,比所有已知优先级的数字都大,所以会排在末尾

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:13:25