Sorting

We need to be able sort:

• arrays alphabetically
• arrays numerically

Sorting Strings

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

• sort() will sort an array of strings in ascending order
• reverse() will sort an array of strings in decending order

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} \${sortedNames} \${sortedNames} \${sortedNames}`)  // 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} \${reverseSortedNames} \${reverseSortedNames} \${reverseSortedNames}`)  // 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>
<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>

<body>
<div>View the console output in browser's Web DevTools (F12)</div>
</body>
</html>

Write code to implement the above two sorts.

We can use the above sort() inline function to sort strings. Write code to do this, 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>