• JavaScript Video Tutorials

JavaScript - TypedArray sort() Method



The JavaScript TypedArray sort() method is used to sort the elements of the current typed array. It returns the reference to the original typed array. Additionally, it accepts an optional parameter named 'compareFn', which defines the sort order of the typed array elements.

The compareFn function should return a number that determines the order of two elements. If the first element (let's say a) is less than the second element (let's say b), the function should return a positive number. If 'a' is greater than 'b', the function should return a negative number. If both elements are equal, the function should return zero.

Syntax

Following is the syntax of JavaScript TypedArray sort() method −

sort(compareFn)

Parameters

This method accepts an optional parameter named 'compareFn', which is described below −

compareFn (optional) − The function that defines the sort order.

Return value

This method returns the reference of the same typed array in sorted order.

Examples

Example 1

In the following example, we are using the JavaScript TypedArray sort() method to sort the elements of the current typed array [30, 25, 10, 15, 8].

<html>
<head>
   <title>JavaScript TypedArray sort() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([30, 25, 10, 15, 8]);
      document.write("TypeArray before sorting: ");
      document.write(T_array);
      T_array.sort();
      document.write("<br>TypedArray after sorting: ");
      document.write(T_array);
   </script>    
</body>
</html>

Output

The above program returns sorted typed array as [8, 10, 15, 25, 30].

TypeArray before sorting: 30,25,10,15,8
TypedArray after sorting: 8,10,15,25,30

Example 2

Here's another example of using the JavaScript TypedArray sort() method. In this example, we create a function named compare (a, b) that compares two parameters, a and b, and returns a - b. We pass this function as an argument to the sort() method to sort the elements of the typed array in ascending order.

<html>
<head>
   <title>JavaScript TypedArray sort() Method</title>
</head>
<body>
   <script>
      function comapre(a, b){
         return a-b;
      }
      const T_array = new Uint8Array([10, 2, 1, 200, 50]);
      document.write("TypedArray before sorting: ", T_array);
      T_array.sort(comapre);
      document.write("<br>TypedArry after sorting: ", T_array);
   </script>    
</body>
</html>

Output

After executing the above program, it will return sorted typedarray as [1, 2, 10, 50, 200].

TypedArray before sorting: 10,2,1,200,50
TypedArry after sorting: 1,2,10,50,200
Advertisements