I have a JSON array of objects that looks something like this:
var garments [{
name: \'Garment 1\',
isDesignable: false,
priority: 3
},{
name: \'
Solution with one line of code.
First build the difference between isDesignable
and if the same apply the difference of priority
as sort indicator.
var garments = [{
name: 'Garment 1',
isDesignable: false,
priority: 3
}, {
name: 'Garment 2',
isDesignable: false,
priority: 1
}, {
name: 'Garment 3',
isDesignable: true,
priority: 3
}, {
name: 'Garment 4',
isDesignable: true,
priority: 2
}, {
name: 'Garment 5',
isDesignable: true,
priority: 4
}];
// sort isDesignable first and then by priority ascending
garments.sort(function (a, b) {
return b.isDesignable - a.isDesignable || a.priority - b.priority;
});
document.write('<pre>' + JSON.stringify(garments, 0, 4) + '</pre>');
// sort reversing the former sort order by sorting, not reversing
garments.sort(function (a, b) {
return a.isDesignable - b.isDesignable || b.priority - a.priority;
});
document.write('<pre>' + JSON.stringify(garments, 0, 4) + '</pre>');
garments.sort(function (a, b) {
if (a.isDesignable == b.isDesignable) {
return a.priority - b.priority;
} else if (a.isDesignable) {
return -1;
} else {
return 1;
}
});