Javascript Lodash按属性排序/排序数组

Javascript Lodash按属性排序/排序数组,javascript,lodash,Javascript,Lodash,我有以下对象数组: var tasks = [ { importance: 'moderate', task: 'do laundry' }, { importance: 'critical', task: 'brush teeth' }, { importance: 'important', task: 'buy milk' }, { importance: 'unimportant', task: 'wash car' }, ]; 如何使用lodash排序或排序函数

我有以下对象数组:

var tasks = [
   { importance: 'moderate', task: 'do laundry' },
   { importance: 'critical', task: 'brush teeth' },
   { importance: 'important', task: 'buy milk' },
   { importance: 'unimportant', task: 'wash car' },
];

如何使用lodash排序或排序函数按重要性级别对数组排序?

首先,将中的重要性值更改为可排序的值,例如整数:

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' },
];`
然后做一些类似的事情:


_.orderBytasks、['importance']、['asc']

首先,将中的重要性值更改为可排序的值,例如整数:

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' },
];`
然后做一些类似的事情:


_.orderBytasks、['importance']、['asc']

您无需使用lodash即可完成:

变量任务=[ {重要性:'中等',任务:'洗衣服'}, {重要性:'关键',任务:'刷牙'}, {重要性:'重要',任务:'买牛奶'}, {重要性:'不重要',任务:'洗车'}, ]; var priorityIndex={不重要:1,中等:2,重要:3,关键:4}; tasks.sorta,b=>priorityIndex[a.重要性]-priorityIndex[b.重要性];
console.logtasks 您可以在不使用lodash的情况下完成:

变量任务=[ {重要性:'中等',任务:'洗衣服'}, {重要性:'关键',任务:'刷牙'}, {重要性:'重要',任务:'买牛奶'}, {重要性:'不重要',任务:'洗车'}, ]; var priorityIndex={不重要:1,中等:2,重要:3,关键:4}; tasks.sorta,b=>priorityIndex[a.重要性]-priorityIndex[b.重要性];
console.logtasks;您最好在重要性值中添加一些整数值。这将使排序变得容易。首先,将重要性值更改为可排序的值,例如整数,然后执行类似于u.orderBytasks、['user']、['asc']的操作;您最好在重要性值中添加一些整数值。这将使排序变得容易。首先,将重要性值更改为可排序的值,例如整数,然后执行类似于u.orderBytasks、['user']、['asc']的操作;错误的评论。。你有我的+1漂亮!谢谢你,先生!错误的评论。。你有我的+1漂亮!谢谢你,先生!