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 ?
Share Improve this question asked May 17, 2018 at 16:15 koryakinpkoryakinp 4,1357 gold badges27 silver badges59 bronze badges 2- you better add some integer value to mart the importance value. That would make it easy to sort – Muhammad Usman Commented May 17, 2018 at 16:18
-
first of all, change the importance value in to something sortable (e.g. integers) and then do something like
_.orderBy(tasks, ['user'], ['asc']);
– sica07 Commented May 17, 2018 at 16:20
2 Answers
Reset to default 8You 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']);