The Starting Point - Arrays - Java Script

You were introduced to the Array object and its sort() method.You may remember that the sort() method sorts in ascending order by the ASCII each item, meaning that numbers are also sorted by their string equivalents:

The previous example displays “2,3,32,5” when the array is output.Luckily,JavaScript doesn’t leave you stranded. The sort() method can also be given a single argument:a comparison function to tell the sorting algorithm when one value is greater than,less than,or equal to another value.

A comparison function is a function with a specific algorithm.It’s helpful to take a look at a basic comparison function before continuing with the explanation:

As you can see, a comparison function compares two values, which is why a comparison function always has two arguments.If the first argument should come before the second argument,the function returns –1. If the first argument should come after the second argument,the function returns 1.If, however, the arguments are equal,the function returns 0. The comparison function is used in the sort() method like this:

arr.sort(comparison_function);

The basic comparison function pattern described previously sorts an array in ascending order.To sort in descending order, you just reverse 1 and –1:

If this pattern sounds familiar, that’s because the String’s localeCompare() method works the same way. So if you are sorting an array of strings, you can use this method directly:

This function causes an array of strings to be sorted in ascending order.To sort an array in descending order,just put a negative sign in front of the call:

By adding the negation operator, 1 becomes –1, –1 becomes 1, and 0 remains unchanged. Now, go back to the previous example, in which numbers are sorted incorrectly.You can easily remedy the problem by writing a comparison function that transforms the arguments into numbers first and then compares them:

If you apply this comparison function to the earlier example,the correct result is returned:

This example now outputs the numbers in correct order (2, 3, 5, 32).

The reverse() method

Reverse() method, is that which simply reverses the order of the items in an array,.Here, you learn that the reverse() method is an essential part of sorting.

So,if you use a comparison function that sorts in ascending order,you can easily change the sort to descending order by using the reverse() method after the sort() method:

Of course, this is an extra step added to the sorting process, and there is certainly nothing wrong with creating two comparison functions whenever sorting is necessary.Just keep in mind that whenever an array is already sorted in one direction, it is much faster to use reverse() to sort it in the opposite direction than it is to call sort() once again.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics