Sort and Search

Site: Philippine Science High School - MC - Knowledge Hub
Course: SY25.CS3.Web Development
Book: Sort and Search
Printed by: , Guest user
Date: Tuesday, 25 November 2025, 9:33 PM

1. Introductions

After completing this module, you are expected to:

      • Understand how other arrays methods can be implemented;
      • Implement JavaScript sort() method; and
      • Use array methods to implement search tasks in JavaScript.

          In the previous lesson, you were introduced to different array methods. These methods were able to help in manipulating your array such as adding or removing an element. In some web applications, it is important that the data gathered are organized. With this searching can easily be implemented.

           In this lesson, you will be able to know how to sort your array and implement searching methods.

2. Sorting an Array

          In order to sort an array, the sort() method is used. Using this method, elements in the array are arranged alphabetically.

For example:

<script>

var region12 = ["South Cotabato", "Cotabato City", "Sultan Kudarat",  

"Sarangani", "General Santos City"];

region12.sort(); //sorts the array alphabetically

console.log(region12);

</script>

          With the example above, it will print ["Cotabato City", "General Santos City", "Sarangani", "South Cotabato", "Sultan Kudarat"]. It is rearranged in an alphabetical order. If you want to reverse the output, the reverse() method can be used.

For example:

<script>

var region12 = ["South Cotabato", "Cotabato City", "Sultan Kudarat",  

"Sarangani", "General  Santos City"];

region12.sort(); //sorts the array alphabetically

region12.reverse(); //reverses the sorted array

console.log(region12); //prints ["Sultan Kudarat", "South Cotabato",

"Sarangani", "General  Santos City", "Cotabato City"]

</script>


3. Sorting Numeric Values

          Using the sort() method, the array values are taken as strings. Thus, the sort() method will result in an incorrect output when sorting numbers. For example, if you sort the number 2 and 10. The number 10 will come first before 2. In order to fix this, a compare function must be added.

For example:

<body>

<h1> JavaScript Array Sort </h1>

<h4> Click the button to sort the array in ascending order </h4>

 <button onclick="myFunctionA()">Sort as String</button>

<button onclick="myFunctionB()">Sort as Number</button>

 <p id="demo"></p>

 <script>

      var points = [5, 10, 1, 25, 100, 40];

       document.getElementById("demo").innerHTML = points; 

       function myFunctionA() {

       points.sort();

       document.getElementById("demo").innerHTML = points;

       }    

       function myFunctionB() {

       points.sort(function(a, b){return a - b});

       document.getElementById("demo").innerHTML = points;

       }

</script>

</body>

          In the example above, two buttons can be clicked. It is the "Sort as String" and "Sort as Number". When the "Sort as String" is clicked, it arranges the array by comparing the ASCII value of the characters in each element. When the two elements have the same ASCII value for its first element, then it compares the value of the second character until the characters are not the same anymore. Because of this, the numerical value is disregarded. Meanwhile, when the other button is clicked, the array is sorted according to its numerical value. See sample output below:

          The compare function works as an alternative way to sort arrays. When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned value. This function returns negative, zero or positive. A negative result will sort a before b. Meanwhile, b is sorted before a when the result is positive while no changes will happen if result is 0.

          The array is sorted in ascending order. In order to reverse it, little modification of the compare function can be done.

 Instead of

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

you can change it to 

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


4. Finding the Minimum and Maximum Value in an Array

          One of the common searches we do in an array is to find the minimum and maximum value. In JavaScript, there are no built-in functions to find the maximum or the minimum value in an array. To do this, you can sort the array first and use the index to look for the highest and lowest values. However, this method seems to be inefficient.

          Using the Math.max.apply() and Math.min.apply(), you can search for the maximum and minimum values, respectively.

For example:

<body>

<h1> Min and Max Value </h1>

<button onclick="findMin(points)">Find Minimum</button>

<button onclick="findMax(points)">Find Maximum</button>

 <p id="demo"></p>

 <script>

            var points = [9, 3, 52, 23, 63, 98, 76];

             function findMin(arr) {

                  var min = Math.min.apply(null, arr);

                  document.getElementById("demo").innerHTML = min;

            }

             function findMax(arr) {

                  var max = Math.max.apply(null, arr);

                  document.getElementById("demo").innerHTML = max;

            }

</script>

</body>


          The Math.max() and Math.min() do not take arrays. It only gets comma separated arguments. Thus, Math.max.apply() and Math.min.apply() were used. These two methods will require two arguments – the this argument and the array. For now, the value used in the first argument does not matter as it will give the same result if we use the values Math, "" or 0. The second argument will take the array that we want to get the minimum and maximum values.

5. Summary and References


Summary:


          In summary, sort() method can be used to arrange elements of the array alphabetically. However, when sorting numerical values, a compare function is needed. It will compare each element of the array and sort them. Sorting arrays will help in finding directly the minimum or maximum value in the array. But this method can be inefficient. You can use the Math.min.apply() and Math.max.apply() method to easily find the minimum and maximum values, respectively.


References:

JavaScript Array Sort. (n.d.-a). Retrieved March 30, 2021, from https://www.w3schools.com/js/js_array_sort.asp

JavaScript Array sort: Sorting an Array More Effectively. (n.d.-b). JavaScript Tutorial. Retrieved March 30, 2021, from https://www.javascripttutorial.net/javascript-array-sort/