How to sort an array of integers correctly JavaScript?


In this article we are going to learn about “how to sort an array of integers correctly JavaScript”. Let’s look into the article to learn more about to sort an array.

Sorting an array of integers is something that we’ve to do a lot in our JavaScript. The sort method lets us sort an array by passing in a comparator function.

Sort() Method

The sort() method enables you to order array elements sequentially. The sort() method modifies the positions of the elements in the initial array in addition to returning the sorted array.

The array elements are ordinarily sorted by the sort() method in ascending order, with the smallest value coming before the largest. In order to determine the ordering, the sort() method converts elements to strings and compares the strings.

Let’s look into the following examples to know more about “how to sort an array of integers correctly in JavaScript.”

Example

In the following example we are using sort() method to sort array in ascending order.

<!DOCTYPE html>
<html>
<body>
   <p>Ascending order of sorting is</p>
   <p id="tutorial"></p>
   <script>
      const points = [24, 144, 54, 2, 66, 77];
      points.sort(function(a, b){return a-b});
      document.getElementById("tutorial").innerHTML = points;
   </script>
</body>
</html>

When the script gets executed, it will generate an output consisting of a list of numbers that was sorted in ascending order by using the sort() method on the webpage.

Example

Considering the following example where we are using the sort() method to sort array in descending order.

<!DOCTYPE html>
<html>
<body>
   <p>Descending order of Sorting is</p>
   <p id="tutorial"></p>
   <script>
      const points = [111, 100, 99, 88, 77, 66];
      points.sort(function(a, b){return b-a});
      document.getElementById("tutorial").innerHTML = points;
   </script>
</body>
</html>

On running the above script, the web-browser displays the list of numbers, which are sorted by using the sort() method on the webpage.

Updated on: 18-Jan-2023

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements