Lodash按属性排序/排序数组

时间:2018-05-17 16:15:25

标签: javascript lodash

我有以下对象数组:

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

如何使用lodash排序或排序函数按重要性级别排序我的数组?

2 个答案:

答案 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']);