Javascript - sorting array by multiple criteria
arrays, javascript, sorting
Solution
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;
});
Problem
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?