Header Ads Widget

Sorting Arrays in JavaScript

 


Like any programming language, JavaScript also provides ways to sort arrays. Different JavaScript engines implement this method using different sort algorithms. For example -

  • Safari: Quicksort, Merge Sort, or Selection Sort
  • V8: Quicksort, or Insertion Sort
  • Firefox: Merge Sort
But in reality, it doesn't really matter much as long as the arrays are getting sorted.

Note - I am putting my JavaScript Developer study notes here

The prototype for Sort method available in Array class is:

Array.sort([compareFunction])

Normally a callback function is passed which makes the sorting logic i.e. how the two numbers will be compared. This callback function should take two parameters i.e. param1 and param2 and works like this -

  • callback function will return zero when both param1 and param2 are treated as equal
  • callback function will return 1 when both param1 is smaller than param2 
  • callback function will return 11 when both param2 is smaller than param1
Note - In default sorting, param1 and param2 are always converted into Strings and then they will be sorted alphabetically.

For example, if we consider the below example

let numbers = [100, 23, 45, 12, 99];
let sortedNumbers = numbers.sort();
console.log(sortedNumbers);

Output

[ 100, 12, 23, 45, 99 ]

But that's not the correct sorting. The reason behind is that numbers here are converted into Strings and then sorted alphabetically due to default sorting.

To solve this we need to pass the callback function which will define the comparison logic. Below is the modified code -

let numbers = [100, 23, 45, 12, 99];
let sortedNumbers = numbers.sort((num1, num2) => num1 - num2);
console.log(sortedNumbers);

Output:

[ 12, 23, 45, 99, 100 ]

Sorting Array of objects

We can use the callback function to define the sort criteria while dealing with the objects as well.
For example, consider the below object, where we are using the sort method to sort array of employees based on their employee numbers.

let employee = [
{ name: "Robert", empNumber: "98" },
{ name: "Kelly", empNumber: "12" },
{ name: "Shane", empNumber: "56" },
{ name: "James", empNumber: "18" },
];

//Sorting based on empNumber
let sortedEmployeed = employee.sort(
(emp1, emp2) => emp1.empNumber - emp2.empNumber
);

console.log(sortedEmployeed);

Output:

[
{ name: 'Kelly', empNumber: '12' },
{ name: 'James', empNumber: '18' },
{ name: 'Shane', empNumber: '56' },
{ name: 'Robert', empNumber: '98' }
]


I have prepared a small video explaining the sort method which is below -


Post a Comment

0 Comments