Array sort( ) method and comparator in Javascript

  1. It sorts the array elements in ascending order by default.
  2. It does not return a new array. It modifies the original array itself to its sorted form.
  3. It casts all the array elements as strings and then sorts them based on UTF-16 code unit values of the first character in the string.
  4. It accepts a comparator function as an argument. Custom logic can be written within the comparator function to sort the array based on different kinds of criteria.
  5. 5. It performs a stable sort.

It sorts the array elements in ascending order by default

When the sort method is applied on an array of letters or strings, it sorts the array elements in alphabetical order.

It modifies the original array itself

The sort method sorts the array elements in-place, that is within the array itself. It does not return a new sorted array. The same array is modified.

It sorts the array based on the UTF-16 code unit values (unicode)

In javascript, all characters have a certain code, including numbers and alphabets.

It accepts a comparator as an argument

A comparator is a function that compares two values and determines the sorting order of the two values. The comparator can be customised to sort strings and object properties as well. Lets see how.

  1. Numeric array
  2. String array
  3. Objects array

Sorting a numeric array

const num = [1, 100, 6, 10]

Sorting an array of strings

Suppose you have an array that you want to sort alphabetically and it is of the following form,

Sorting object property values

If you apply sort( ) directly to an array of objects, it does nothing to the array. The object however, could have properties that need to be sorted. You have to access the properties with the dot notation in the comparator to sort them.

It performs a stable sort

Suppose you have an array of objects with two properties, name and age.

Activity 1

Consider an array of objects

Solution

Total marks of each student is nothing but course1 + course2.

Activity 2

Say you have an array of objects

Solution

movies.sort(function(a,b){

Explanation

If a.imdb-b.imdb expression evaluates to 0 (i.e if the imdb ratings are the same), it will proceed with evaluating || expression -and return the result of a.rottenTomatoes-b.rottenTomatoes.

Wrap Up

The comparator function in sort thus proves to be very versatile for various kinds of applications. When sort( ) is used along with other higher order functions of javascript, it becomes an even more powerful tool. Further reading will involve how to reduce the complexity of sort( ) with the help of other higher order functions such as map( ) in javascript.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store