I have an array of objects:
var arr = [
{title:'50 - 50'},
{title:'100 - 100'},
{title:'50 - 65'},
{title:'100 - 125'}
];
I'm attempting to sort this array so that the items appear in the following order:
var arr = [
{title:'50 - 50'},
{title:'50 - 65'},
{title:'100 - 100'},
{title:'100 - 125'}
];
Currently I'm using the following sorting function to attempt this:
arr.sort(function(a, b){
var titleA = a.title;
var titleB = b.title;
var arrA = titleA.split(' - ');
var arrB = titleB.split(' - ');
var keyA = parseInt(arrA[0]),
keyB = parseInt(arrB[0]);
// Compare the 2 keys
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
However, this returns the items in the following order:
var arr = [
{title:'50 - 65'},
{title:'50 - 50'},
{title:'100 - 125'},
{title:'100 - 100'}
];
It looks like I need to sort by the first number in the title and then the second number. Any ideas?
The sort() callback function usually receives two arguments, say a and b, which are nothing but two elements of the array on which sort() was called and the callback function runs for each possible pair of elements of the array.
JavaScript Array sort()The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
Try this:
arr.sort(function(a, b){
var titleA = a.title;
var titleB = b.title;
var arrA = titleA.split(' - ');
var arrB = titleB.split(' - ');
var keyA1 = parseInt(arrA[0]), keyA2 = parseInt(arrA[1])
keyB1 = parseInt(arrB[0]), keyB2 = parseInt(arrB[1]);
// Compare the 2 keys
if (keyA1 < keyB1) return -1;
if (keyA1 > keyB1) return 1;
if (keyA2 < keyB2) return -1;
if (keyA2 > keyB2) return 1;
return 0;
});
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