JavaScript Array sorting

Array is built-in object in JavaScript. There are many methods in Array object. One of the important method is sort method. This is used to sort the array as name implies.

We will see some interesting examples on sorting the array –

Simple sort

var numbers = [4,3,4,2,5,6,3];
var sorted = numbers.sort(); // ascending order
console.log(sorted);

Sort function converts the numbers into Unicode string and then it sorts. So it is not reliable. Consider example –

var numbers = [80,9,4,3,4,2,5,6,3];
var sorted = numbers.sort(); // ascending order
console.log(sorted);

//Output - 
[2, 3, 3, 4, 4, 5, 6, 80, 9]

This is because 80 comes before 9 in Unicode.

compareFunction

Sort also takes comparator function as argument. compare function takes two arguments and should return -1, 0 or 1 depending on compare condition of arguments ‘less than’, ‘equal’ or ‘greater than’. Lets check few examples to make this clear.

Sorting the array of objects

var students = [
  {name:"John",age:"20"},
  {name:"Richard",age:"18"},
  {name:"Alan",age:"32"},
  {name:"Yann",age:"35"},
  {name:"Natasha",age:"35"},
  {name:"Jennifer",age:"40"},
]

// we cannot sort this array simply by sort function, we have to pass 
// compareFunction here.
// we are sorting based on age
var sorted = students.sort(function(a,b){
  //if a < b return -1
  if(a.age < b.age) {
    return -1;
  } else if(a.age == b.age) {
    return 0;
  } else {
    return 1;
  }
});

console.log(sorted);

Sorting on multiple conditions

Now consider situation where I want to sort the array based on age, but when age is same I want to sort according to name. To achieve this we have to modify condition where we have returned 0 in above code.

var students = [
  {name:"John",age:"20"},
  {name:"Richard",age:"18"},
  {name:"Alan",age:"32"},
  {name:"Yann",age:"35"},
  {name:"Natasha",age:"35"},
  {name:"Jennifer",age:"40"},
]

// we cannot sort this array simply by sort function, we have to pass 
// compareFunction here.
// we are sorting based on age
var sorted = students.sort(function(a,b){
  //if a < b return -1
  if(a.age < b.age) {
    return -1;
  } else if(a.age == b.age) {
    // age is same, now sort by name
    if(a.name < b.name) {
      return -1;
    } else if (a.name == b.name){
      return 0;
    } else {
      return 1;
    }
  } else {
    return 1;
  }
});

// age for Natasha and yann is same, Natasha should printed before Yann
// as per sorting by name

console.log(sorted);

Sorting on custom sort condition

Apart from sorting by comparing, we can sort by custom conditions also. Consider I have array of numbers and I want to move all even numbers to start of array and odd number after that.

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12];

var sorted = numbers.sort(function(a,b){
  if(a%2 == 0 && b%2 != 0) {
    return -1;
  } else if ((a%2 == 0 && b%2 == 0) || (a%2 != 0 && b%2 != 0)) {
    return 0;
  } else {
    return 1;
  }  
});

console.log(sorted);

// Output -
// [12, 10, 4, 8, 6, 2, 7, 1, 11, 3, 9, 5]

Now lets modify above code to sort the even and odds in ascending order. To achieve this we have to add some checks when both the numbers compared are even.

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,80,9];

var sorted = numbers.sort(function(a,b){
  if(a%2 == 0 && b%2 != 0) {
    return -1;
  } else if ((a%2 == 0 && b%2 == 0) || (a%2 != 0 && b%2 != 0)) {
    // both the numbers are even 
    // now sort by ascending
    if (a < b) {
     return -1;
    } else if (a == b) {
      return 0;
    } else {
      return 1;
    }
  } else {
    return 1;
  }  
});

console.log(sorted);

// Output -
// [2, 4, 6, 8, 10, 12, 1, 3, 5, 7, 9, 11]

Thats all about sort function. If any issues or doubts let me know in comments.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s