简体   繁体   中英

Lodash sort/order array by property

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 ?

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 (eg 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']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM