Tutorial: Sorting In Javascript

#### By Emmanuel Chinonso

Web Developer

## JavaScript Sorting Arrays

**Sorting an Array**

The sort() method alphabetically sorts an array:

**JavaScript Code:**

1 var fruits = ['Banana', 'Orange', 'Apple', 'Mango']; 2 fruits.sort(); // Sorts the elements of fruits

**Reversing an Array**
The reverse() method reverses an array's elements. It can be used to sort an array in descending order as follows:

**JavaScript Code:**

1 var fruits = ['Banana', 'Orange', 'Apple', 'Mango']; 2 fruits.sort(); // First sort the elements of fruits 3 fruits.reverse(); // Then reverse the order of the elements

**Numeric Sort:**
The sort() function arranges data as strings by default. This is great for strings ("Apple" comes before "Banana").
When numbers are arranged as strings, however, "25" is more than "100," because "2" is greater than "1."
As a result, when sorting numbers, the sort() method will return an inaccurate result. This can be remedied by including a comparison function:

**JavaScript Code:**

1 var points = [40, 100, 1, 5, 25, 10]; 2 points.sort(function(a, b) { 3 return a - b; 4 });

Use the same trick to sort an array descending:

**JavaScript Code:**

1 var points = [40, 100, 1, 5, 25, 10]; 2 points.sort(function(a, b) { 3 return b - a; 4 });

**The Compare Function**
The comparison function's goal is to define a different sort order. Depending on the arguments, the comparison function should return a negative, zero, or positive value:

`function(a, b){return a - b}`

When the sort() method compares two numbers, it passes them to the compare function, which sorts them based on the (negative, zero, positive) value returned. If the outcome is negative, an is ranked first, followed by b. If the outcome is positive, b is ranked first, followed by a. If the result is 0, no modifications to the two values' sort order are made.

**Example:**
The compare function compares two values at a time throughout the entire array (a, b). The sort() method uses the compare function to compare 40 and 100. (40, 100).
The sort function sorts 40 as a number less than 100 since the function calculates 40 - 100 (a - b) and the result is negative (-60).
You may play about with numerical and alphabetical sorting using this code snippet:

1 <button onclick="myFunction1()">Sort Alphabetically</button> 2 <button onclick="myFunction2()">Sort Numerically</button> 3 <p id="demo"></p> 4 5 <script> 6 var points = [40, 100, 1, 5, 25, 10]; 7 document.getElementById("demo").innerHTML = points; 8 function myFunction1() { 9 points.sort(); 10 document.getElementById("demo").innerHTML = points; 11 } 12 function myFunction2() { 13 points.sort(function(a, b){return a - b}); 14 document.getElementById("demo").innerHTML = points; 15 } 16 </script>

**Sorting an Array in Random Order**

**JavaScript Code:**

1 var points = [40, 100, 1, 5, 25, 10]; 2 points.sort(function(a, b) { 3 return 0.5 - Math.random(); 4 });

**The Fisher Yates Method**

The array.sort() function in the above code is not accurate; it favors some values over others. The Fisher Yates shuffle is the most popular right method, and it was first used in data science in 1938! The method can be converted into JavaScript as follows:

**JavaScript Code:**

1 var points = [40, 100, 1, 5, 25, 10]; 2 for (i = points.length - 1; i > 0; i--) { 3 j = Math.floor(Math.random() * i); 4 k = points[i]; 5 points[i] = points[j]; 6 points[j] = k; 7 }

**Find the Highest (or Lowest) Array Value**

In an array, there are no built-in functions for finding the maximum or minimum value. You can use the index to get the highest and lowest values after you've sorted an array.

**Sorting ascending:**

**JavaScript Code:**

1 var points = [40, 100, 1, 5, 25, 10]; 2 points.sort(function(a, b) { 3 return a - b; 4 }); 5 // now points[0] contains the lowest value 6 // and points[points.length-1] contains the highest value

**Sorting descending:**

**JavaScript Code:**

1 var points = [40, 100, 1, 5, 25, 10]; 2 points.sort(function(a, b) { 3 return b - a; 4 }); 5 // now points[0] contains the highest value 6 // and points[points.length-1] contains the lowest value

If you only want to find the top (or lowest) value, sorting an entire array is wasteful.

**Using Math.max() on an Array:**
To determine the highest number in an array, use Math.max.apply:

**JavaScript Code:**

1 function myArrayMax(arr) { 2 return Math.max.apply(null, arr); 3 } 4 Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).

**Using Math.min() on an Array:**
To determine the lowest value in an array, use Math.min.apply:

**JavaScript Code:**

1 function myArrayMin(arr) { 2 return Math.min.apply(null, arr); 3 } 4 5 Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).

**My Min / Max JavaScript Methods**

Using a "home-made" approach is the quickest solution. This function iterates across an array, comparing each value to the highest value found:

**JavaScript Code: (Find Max)**

1 function myArrayMax(arr) { 2 var len = arr.length; 3 var max = -Infinity; 4 while (len--) { 5 if (arr[len] > max) { 6 max = arr[len]; 7 } 8 } 9 return max; 10 }

This function iterates across an array, comparing each value to the lowest value found:

**JavaScript Code: (Find Min)**

1 function myArrayMin(arr) { 2 var len = arr.length; 3 var min = Infinity; 4 while (len--) { 5 if (arr[len] < min) { 6 min = arr[len]; 7 } 8 } 9 return min; 10 }

**Sorting Object Arrays:**
Objects are frequently found in JavaScript arrays

**JavaScript Code:**

1 var cars = [ 2 { type: 'Volvo', year: 2016 }, 3 { type: 'Saab', year: 2001 }, 4 { type: 'BMW', year: 2010 }, 5 ];

The sort() method can be used to sort an array even if its properties are of different data types. To compare the property values, write a compare function like follows:

**JavaScript Code:**

1 cars.sort(function(a, b) { 2 return a.year - b.year; 3 });

It's a little trickier to compare string properties:

**JavaScript Code:**

1 cars.sort(function(a, b) { 2 var x = a.type.toLowerCase(); 3 var y = b.type.toLowerCase(); 4 if (x < y) { 5 return -1; 6 } 7 if (x > y) { 8 return 1; 9 } 10 return 0; 11 });

## Create Stunning websites and web apps

Trying to build out all user interfaces and components for your website or web app from scratch can become a very tedious task. A huge reason why we created Contrast Bootstrap to help reduce the amount of time we spend doing that, so we can focus on building some other aspects of the project. Contrast Bootstrap PRO consists of a UI Kit featuring over 10000+ component variants. Together with a template of 5 admin dashboards and 23+ additional multipurpose pages template for building almost any type of website or web app. You can view a demo and learn more about Contrast by clicking here.Try contrast pro

Contrast Bootstrap PRO was built using the most popular CSS framework Bootstrap to help build your next landing, admin SAAS, prelaunch etc project with a clean, prebuilt and well documented template and UI components.Learn more about Contrast

Related Posts

Comments

...