Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - sorting array by multiple criteria

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?

like image 835
user2866434 Avatar asked Feb 17 '15 11:02

user2866434


People also ask

How do you sort an array with two conditions?

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.

Can you sort an array in JavaScript?

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.


1 Answers

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;
});
like image 72
Alex Kopachov Avatar answered Oct 13 '22 18:10

Alex Kopachov