I am trying to sort an array of objects on multiple levels based on various keys in the objects.
For example, say there is a value inside the object that should be in ascending order, and there is a priority flag, the output should have the objects with the priority flag on top and then the other ones, and both sets should be sorted on the values
I/P: array of Objects (with a value and a priority flag)
var inputArray = [
{ value: 200, hasPriority: false},
{ value: 100, hasPriority: false},
{ value: 80.7, hasPriority: false},
{ value: 85, hasPriority: false},
{ value: 90, hasPriority: false},
{ value: 100, hasPriority: false},
{ value: 100, hasPriority: false},
{ value: 65, hasPriority: false},
{ value: 100, hasPriority: false},
{ value: 120, hasPriority: true},
{ value: 195, hasPriority: true},
{ value: 120, hasPriority: false}
]
O/P: Sorted Array having the objects in ascending order of their values, with the prioritized objects on top.
So the output should have the
{
value: 120,
hasPriority: true
}
on top followed by the other objects in ascending order
What I tried? I tried running sort on the list twice. Initially, to sort based on the values and then on the flags. However, by the end of the second sort, thought the object with hasPriority is put on top, the other values lose their sorted order.
My sorting methods were
function(a,b){
if(a.value < b.value) return -1;if(a.value > b.value) return 1; return 0;
}
and
function(a,b){
if(a.hasPriority) return -1; if(b.hasPriority) return 1; return 0;
}
Kindly let me know if there is any good way of doing this other than running through the list after initial sort and pulling values to the front after the first condition.
Also, I may have to work with additional levels of sorting. There may be other flags that would override the others in a third level of sorting.
Each subsequent level of sorting would need to keep the existing sorted order among the sets