I have an array of objects of the following form:
arr[0] = { 'item1' : 1234, 'item2' : 'a string' };
I sort it first by 'item1'
which is straightforward. Now i want to sort arr
(which is sorted by 'item1'
) again but this time by 'item2'
but only for the elements where 'item1'
is the same. The final array would look like:
arr = [
{ 'item1' : 1234, 'item2' : 'apple' },
{ 'item1' : 1234, 'item2' : 'banana' },
{ 'item1' : 1234, 'item2' : 'custard' },
{ 'item1' : 2156, 'item2' : 'melon' },
{ 'item1' : 4345, 'item2' : 'asparagus' }
];
I tried to write a sorting function for the second case like so:
arr.sort(function(a,b){
if(a.item1 === b.item1){
return a.item2 > b.item2 ? 1 : a.item2 < b.item2 : -1 : 0;
}
});
I could combine the two sorts in one function to get the final sorted array but there will be cases where I'll have to sort by just 'item1'
or just 'item2'
.