Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort custom comparator function - sorting a sorted array

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'.

like image 908
fenderplayer Avatar asked Aug 23 '11 07:08

fenderplayer


People also ask

How do you sort a custom array?

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.

How do you sort an array based on an object's value in JavaScript?

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.


1 Answers

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; }); 
like image 90
Petar Ivanov Avatar answered Sep 16 '22 14:09

Petar Ivanov