Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort an array of objects with two keys in javascript

I have an array of objects and I want to sort it based on two keys.

var data = [{COMPONENT: 'PM-ABC', PRIORITY: '0.35'},
            {COMPONENT: 'PM', PRIORITY: '0.35'}
            {COMPONENT: 'PM', PRIORITY: ''}]

It should first sort on key COMPONENT (Ascending order) and then on PRIORITY (” should come before number say ‘0.35’)

I have tried below code which sorts based on only key i.e COMPONENT

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data.sort(function (a, b) {
            return (a['COMPONENT'] > b['COMPONENT']) ? 1 : (a['COMPONENT'] < b['COMPONENT']) ? -1 : 0;
        });

I am expecting below result

data = [{COMPONENT: 'PM', PRIORITY: ''}
        {COMPONENT: 'PM', PRIORITY: '0.35'}
        {COMPONENT: 'PM-ABC', PRIORITY: '0.35'}]

>Solution :

You can use String#localeCompare.

let data = [{COMPONENT: 'PM-ABC', PRIORITY: '0.35'},
            {COMPONENT: 'PM', PRIORITY: '0.35'},
            {COMPONENT: 'PM', PRIORITY: ''}];
data.sort((a,b) => a.COMPONENT.localeCompare(b.COMPONENT) ||
  a.PRIORITY.localeCompare(b.PRIORITY));
console.log(data);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading