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'
.
To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.
To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
You can have four different comparison functions - one sorting by item1, one by item2, one by item1 then item2 and one by item2 then item1.
E.g.:
arr.sort(function(a,b){ if(a.item1 == b.item1){ return a.item2 > b.item2 ? 1 : a.item2 < b.item2 ? -1 : 0; } return a.item1 > b.item1 ? 1 : -1; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With