JavaScript .sort() method

JavaScript has a built-in sorting prototype method for array data structure called .sort(). Which can be used to sort elements of an array. When we call .sort() method of an array of numbers or strings JavaScript automatically sort the array.

Sort array of numbers

let values = [25, 23, 10, 15]
values.sort()

.sort() will mutate the original array.

values
// [10, 15, 23, 25]

Remember .sort() method will sort based on alphabetic order, example

let results = [5, 10, 7, 6]
results.sort()
results; // [10, 5, 6, 7]

Sort array of strings

let names = ["David", "Mark", "Adam", "John"]
names.sort()
names;
// ["Adam", "David", "John", "Mark"]

Sort array of numbers and strings

let values = [18, 15, "B", "a", "c"]
values.sort()
// [15, 18, "B", "a", "c"]

Sort array of object

For numbers or strings we can easily perform sort. But for array of object we need to write a custom compare function. Lets look at this example,

let products = [
  { id: 1, title: "Samsung", price: 500 },
  { id: 2, title: "Oppo", price: 300 },
  { id: 3, title: "iPhone", price: 800 }  
]

Custom compare function(if we want to sort based on the price, ascending order),

function sortByPrice(a, b) {
  return a.price - b.price;
}

sortByPrice is a compare function, which compares two price from two object. In case you need descending order, write b.price - a.price. As .sort() is a higher order function we can put the sortByPrice inside the .sort() method.

products.sort(sortByPrice)

Now if we log the products array,

[
  { id: 2, title: 'Oppo', price: 300 },
  { id: 1, title: 'Samsung', price: 500 },
  { id: 3, title: 'iPhone', price: 800 }
]

Lets discuss what is actually happening,

  • the compare function(sortByPrice) first compares between id 2 & id 1, 300 – 500 result is -200 as it is negative so id 2 will be moved before id 1.
  • then id 3 & id 2, 800 – 300 result is 500 as it is a positive so id 3 will be moved after id 2.
  • id 3 & id 1, 800 – 500 result is 300 as it is positive so id 3 will be moved after id 1.

Lets look at a new similar example, sorting based on date of birth,

let users = [
  { id: 1, name: "Mark", dob: "1994-10-21" },
  { id: 2, name: "John", dob: "1993-05-10" },
  { id: 3, name: "David", dob: "1995-06-12" }
]

So the compare function will be,

function sortByDOB(a, b) {
    return new Date(a.dob).valueOf() - new Date(b.dob).valueOf();
}

users.sort(sortByDOB)

So the users array,

[
  { id: 2, name: 'John', dob: '1993-05-10' },
  { id: 1, name: 'Mark', dob: '1994-10-21' },
  { id: 3, name: 'David', dob: '1995-06-12' }
]

2 thoughts on “JavaScript .sort() method”

Leave a Comment

Your email address will not be published. Required fields are marked *