Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
We need to be able sort:
There are two sorting methods that will sort an array of strings:
The array can contain strings.
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.
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.
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.
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.