我有以下对象数组:
var tasks = [
{ importance: 'moderate', task: 'do laundry' },
{ importance: 'critical', task: 'brush teeth' },
{ importance: 'important', task: 'buy milk' },
{ importance: 'unimportant', task: 'wash car' },
];
如何使用lodash排序或排序函数按重要性级别排序我的数组?
答案 0 :(得分:5)
你可以不用lodash这样做:
var tasks = [
{ importance: 'moderate', task: 'do laundry' },
{ importance: 'critical', task: 'brush teeth' },
{ importance: 'important', task: 'buy milk' },
{ importance: 'unimportant', task: 'wash car' },
];
var priorityIndex = {unimportant: 1, moderate: 2, important: 3, critical: 4};
tasks.sort((a, b) => priorityIndex[a.importance] - priorityIndex[b.importance]);
console.log(tasks);

答案 1 :(得分:2)
首先,将importance
值更改为可排序的值(例如整数):
const critical = 1;
const important = 2;
const moderate = 3;
const unimportant = 4;
var tasks = [
{ importance: moderate, task: 'do laundry' },
{ importance: critical, task: 'brush teeth' },
{ importance: important, task: 'buy milk' },
{ importance: unimportant, task: 'wash car' },
];`
然后执行以下操作:
_.orderBy(tasks, ['importance'], ['asc']);