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?