I have a following array of objects:
var tasks = [
{ importance: 'moderate', task: 'do laundry' },
{ importance: 'critical', task: 'brush teeth' },
{ importance: 'important', task: 'buy milk' },
{ importance: 'unimportant', task: 'wash car' },
];
How can I use lodash sort or order functions to order my array by level of importance ?
I have a following array of objects:
var tasks = [
{ importance: 'moderate', task: 'do laundry' },
{ importance: 'critical', task: 'brush teeth' },
{ importance: 'important', task: 'buy milk' },
{ importance: 'unimportant', task: 'wash car' },
];
How can I use lodash sort or order functions to order my array by level of importance ?
_.orderBy(tasks, ['user'], ['asc']);
– sica07
Commented
May 17, 2018 at 16:20
You can do it without 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);
first of all, change the importance
value in to something sortable (e.g. integers):
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' },
];`
and then do something like:
_.orderBy(tasks, ['importance'], ['asc']);