If I have an array of below items and I want to display all the IsImportant=true items sorted first and then IsImportant=false items sorted next.
var sampleArray = [{
"Name": "A",
"IsImportant": true
}, {
"Name": "B",
"IsImportant": true
}, {
"Name": "C",
"IsImportant": false
}, {
"Name": "D",
"IsImportant": false
}, {
"Name": "E",
"IsImportant": false
},, {
"Name": "F",
"IsImportant": true
},
, {
"Name": "G",
"IsImportant": true
}, {
"Name": "H",
"IsImportant": false
}];
I was trying to write a compareFunction like below to reach the result but didn't succeed. Would there be any better alternative?
function comparator(a, b) {
//console.log(a,b);
if (a.IsImportant || b.IsImportant) {
if (a.Name > b.Name) {
return 1;
}
if (a.Name < b.Name) {
return -1;
}
}
return 0;
};
return b.IsImportant - a.IsImportant || a.Name.localeCompare(b.Name);