Is there a way in jQuery or javascript to sort the data by category in descending order and name in ascending order?
I have tried to sort the data twice similar to the sample code below, but it's not working as it should be.
The data should be listed by category like B, A and will sort next by name like AA, AB, BB and so on.
Sample data and sort script:
var data = {
0: {
category: 'A',
name: 'AA'
},
1: {
category: 'B',
name: 'BB'
},
2: {
category: 'A',
name: 'AB'
},
3: {
category: 'A',
name: 'BB'
}
}
var items = $( $.map( data, function ( val, i ) {
return val;
} ) );
// Sort data by category in DESC order.
function sortByCategoryDescOrder( a, b ) {
if ( a.category < b.category ) {
return -1;
}
if ( a.category > b.category ) {
return 1;
}
return 0;
}
function sortByNameAscOrder( a, b ) {
if ( a.name < b.name ) {
return -1;
}
if ( a.name > b.name ) {
return 1;
}
return 0;
}
items.sort(sortByCategoryDescOrder);
items.sort(sortByNameAscOrder);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
The expected output should be:
var data = {
0: {
category: 'B',
name: 'BB'
},
1: {
category: 'A',
name: 'AA'
},
2: {
category: 'A',
name: 'AB'
},
3: {
category: 'A',
name: 'BB'
}
}