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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With