简体   繁体   English

Lodash按属性排序/排序数组

[英]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 ? 如何使用lodash排序或排序函数按重要性级别对数组排序?

You can do it without lodash: 您可以不用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): 首先,将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' },
];`

and then do something like: 然后执行以下操作:

_.orderBy(tasks, ['importance'], ['asc']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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