Sorting

We need to be able sort:

Sorting Strings

There are two sorting methods that will sort an array of strings:

The array can contain strings.

sort()

The sort() method sorts an array of strings in ascending order. The sort() method does not work on arrays of numbers.

sort() applied to an array of strings

let names = ["Allen", "Mary", "Betty", "John"]

let sortedNames = names.sort()

console.log(`${sortedNames[0]} ${sortedNames[1]} ${sortedNames[2]} ${sortedNames[3]}`)  // will display "Allen" "Betty" "John" "Mary"

Write code to implement the above sort.

reverse()

The reverse() method sorts an array of strings in decending order. The reverse() method does not work on arrays of numbers.

reverse() applied to an array of strings

let names = ["Allen", "Mary", "Betty", "John"]

let reverseSortedNames = names.reverse()

console.log(`${reverseSortedNames[0]} ${reverseSortedNames[1]} ${reverseSortedNames[2]} ${reverseSortedNames[3]}`)  // will display "Mary" "John" "Betty" "Allen

Write code to implement the above reverse sort.

Sorting Numbers

The default sort() method sorts by ASCII value, so it cannot be used to sort numbers. In order to sort numbers, we pass a function into the sort() method.

Use the code below to sort an array of numbers in ascending or decending order (Run Example)

<!DOCTYPE html>
<html>
    <head>
        <title>Sort array of numbers in ascending order example</title>
        <meta http-equiv="Content-Type" content="text/htmlcharset=utf-8">
        <meta http-equiv="Content-Language" content="en" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
      
        <script>
            let numbers = [22, 20, 23, 19]
 
            // Sort in ascending order
            let ascendingOrder = numbers.sort((a, b) => a < b?-1:1)
            console.log(`ascendingOrder: ${ascendingOrder}`)

            // Sort in decending order
            let descendingOrder = numbers.sort((a, b) => a < b?1:-1)
            console.log(`descendingOrder: ${descendingOrder}`)
        </script>
    </head>
    
    <body>         
         <div>View the console output in browser's Web DevTools (F12)</div>
    </body>
</html>

We can use the above sort() inline function to sort strings. Write code to do this, as shown here.

Write code to sort all the even numbers in an array, as shown here.

 

 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>