By: Craig Buckler
We can use the standard array sort() method to rearrange the values into logical order:
What result will be output?
The result may surprise you. While you would expect [1, 2, 9, 15, 30], the actual output is a seemingly random [1, 15, 2, 30, 9].
The reason is logical once you understand how the sort() method operates. An array may contain numerous types of value; integers, real numbers, strings, objects, etc. When the sort() method is used without a parameter, every value is converted to a string representation and sorted in lexicographic order, e.g. “15” will come before “2” because the first character – “1” – is lower than “2”. Similarly, “Banana” will appear before “apple” because an uppercase “B” is lower than “a” in the character set.
While string comparison has uses, it’s not the result we need. Fortunately, the array sort() method can be passed a comparison function as a parameter.
The comparison function expects two parameters – a and b – which are values from the array being sorted. The function must return a numeric value:
- if a is greater than b, the returned value must be positive (above zero)
- if a is smaller than b, the returned value must be negative (below zero)
- if a and b are equivalent, the returned value must be zero
You can therefore define a function to sort an array of numbers from lowest to highest value:
This can be simplified since subtracting b from a will also return a valid comparison value:
The SortLowToHigh comparison function can be passed to the array sort method:
Note: do not add () brackets after SortLowToHigh; we are providing a reference to that function rather than calling it.
The array is now sorted as we expect: [1, 2, 9, 15, 30].
If a comparison is used multiple times in your code, it’s practical to create a named function such as SortLowToHigh above.
The comparison function provides incredible flexibility and we can sort arrays of variables or objects using any criteria. For example, we can define named map locations as objects in an array:
Sorting the map array by the object ‘name’ can be achieved using a comparison function which references that property:
Or we could sort locations by their shortest distance from any location. First, we’ll define a simple function which uses Pythagoras to calculate the distance between two co-ordinate objects:
This can then be used within a simple comparison function to determine the closest locations from ‘home’ (0, 0):
Alternatively, we could permit the user to enter any location in an HTML form:
then intercept their form submission and calculate the closest map point: