Sorting an array using Array.sort() in Javascript

js.srijan

Table of Contents

Introduction

In Javascript, Array.sort() is a built-in method of the Array Object. Using Array.sort(), we can sort arrays in descending or ascending order. The default sort order is ascending order for the sort method.

Different browsers use different sorting algorithms for Array.sort(). Mozilla uses merge sort while chrome's javascript V8 engine uses quicksort and insertion sort.

Syntax

arr.sort([compareFunction]);

[compareFunction] is an optional argument of the sort method. It determines the sort order. If omitted, the values of the array will be converted to strings and compared based on their Unicode code point values.

let arr = [9, 70, 44]; arr.sort(); // As no compare method is provided, // the array elements will be converted to strings("9", "70", "44") and // their unicode code point value will be compared. console.log(arr); // 44, 70, 9

Compare Function

Compare Function takes two values in the array as parameters for comparing and deciding the sort order. You can define the condition for comparing the values, which will decide the sort order.

// A simple compare function to sort // an array of numbers in ascending order. function (a, b) { return a - b; }

Compare Function decides the order of values based on the following conditions:

  • If it returns a negative number, the index of "a" will be lower than "b".
  • If it returns a positive number, the index of "a" will be higher than "b".
  • If it returns 0, it leaves the element at its place.

Note: The array is sorted in place and the sort method also returns the sorted array.

Example:

let arr = ["a", "c", "b"] let sortedArr = arr.sort() console.log(arr); // ["a", "b", "c"] console.log(sortedArr); // ["a", "b", "c"]

Let's work with a few examples to understand Array.sort() better.

Sorting numbers without compare function

let arr = [9, 70, 44]; arr.sort(); // [44, 70, 9]

Sorting numbers with compare function

let compareFunc = (a,b) => a-b; arr.sort(compareFunc); //[9, 44, 70]

Sorting strings

let arr = ["John Doe","love","javascript"]; arr.sort(); //["John Doe", "javascript", "love"] // Unicode code point value of first letter of every word is compared // and ordered in ascending order.

Sorting an array of numbers and strings

arr = ["John Doe", "eats", 3, "apples"] arr.sort(); [3, "John Doe", "apples", "eats"] // Number is converted to string and Unicode code point values of all // elements are compared and ordered in ascending order.

Sorting an array having undefined as an element

// All undefined elements are sorted to the end of the array. // Compare function is not called for undefined. let arr = ["zoo","have", 4, "dino", undefined, "mammoth"]; //[4, "dino", "have", "mammoth", "zoo", undefined]

Share this

Share on social media