Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array based on multiple values

Tags:

javascript

I am trying to sort the below array, based on multiple values, report_yr and report_qtr, the array should be sorted according to year first and then as per quarter(for that same year).

// input array

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

// expected output:

[ 
{ 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' } ];

// What I am trying:

I am trying to use loadash methods for this,

_.sortBy(arr,
      ['report_yr', 'report_qtr']);

Similarly tried with orderBy but no luck so far.

like image 500
K S Avatar asked Mar 12 '26 20:03

K S


1 Answers

You can use sort method and do this with plain 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)
like image 172
Nenad Vracar Avatar answered Mar 14 '26 08:03

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!