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
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);