最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash sortorder array by property - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

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

发布评论

评论列表(0)

  1. 暂无评论