我正在尝试根据多个值report_yr和report_qtr对下面的数组进行排序,
数组应首先按年份排序,然后再按季度(同一年)排序。

//输入数组

let arr = [{
  report_yr: '2008',
  report_qtr: '1'
},
{
  report_yr: '2019',
  report_qtr: '3'
},
{
  report_yr: '2019',
  report_qtr: '4'
},
{
  report_yr: '2017',
  report_qtr: '2'
},
{ report_yr: '2008',
  report_qtr: '2'
}];

//预期输出:
[
{ report_yr: '2019',
report_qtr: '4' },
{ report_yr: '2019',
report_qtr: '3' },
{ report_yr: '2008',
report_qtr: '1'
},{ report_yr: '2008',
report_qtr: '2'
},
{ report_yr: '2017',
report_qtr: '2' } ];

//我正在尝试:

我正在尝试为此使用loadash方法,
_.sortBy(arr,
      ['report_yr', 'report_qtr']);

同样尝试了orderBy,但到目前为止还没有运气。

最佳答案

您可以使用sort方法,并使用简单的javascript做到这一点。

let arr = [{"report_yr":"2008","report_qtr":"1"},{"report_yr":"2019","report_qtr":"3"},{"report_yr":"2019","report_qtr":"4"},{"report_yr":"2017","report_qtr":"2"},{"report_yr":"2008","report_qtr":"2"}]

arr.sort((a, b) => b.report_yr - a.report_yr || b.report_qtr - a.report_qtr)
console.log(arr)

09-28 12:58
查看更多