When working with arrays in Javascript one of the most common programming is organizing it. Often the data are entered and need to sort them in order to facilitate the implementation of this type of function two methods are widely used and we know them now.
REVERSE
With this method it has to invert the position of an array, the latter elements become the first example as shown below:
<SCRIPT LANGUAGE=”JavaScript” TYPE=”text/javascript”>
var vet = Array (1, 2, 3, 4, 5);
document.write (“Normal array: ” + vetor);
document.write (” and Inverted array: ” + vetor.reverse());
</SCRIPT>
What will be printed on the screen will be “Normal array: 1,2,3,4,5 and Inverted Array: 5,4,3,2,1”.
SORT
This method is responsible for ordering an array in alphabetical order. Informing the variable with the data automatically it is ordered, check the example:
<SCRIPT=”JavaScript” TYPE=”text/javascript”>
var vetor = Array (“Blue”, “Yellow”, “Red”, “Black”);
document.write (vetor.sort());
</SCRIPT>
The result on the screen is “Black, Blue, Red, Yellow.”
For this type of organization the SORT method works very well, the problems start when you need to order a numeric array in increasing or decreasing. To perform this action you need to implement two other complementary methods that will help you identify the method SORT which will come first position in the array.
<SCRIPT LANGUAGE=”JavaScript” TYPE=”text/javascript”>
function cres (pr1, pr2){
return pr1 – pr2;
}
function decr (pr1, pr2){
return pr2 – pr1;
}
var vetOr = Array (12, 1, 10, 20);
var vetCres = vetOr;
var vetDecr = vetOr;
document.write (“Vector Ascending: “);
document.write (vetCres.sort(cres));
document.write (“<BR>Vector Descending: “);
document.write (vetDecr.sort(decr));
</SCRIPT>
Using the methods and growing decr sort method able to sort numbers and thus have the result of this implementation, as follows:
Vector Ascending Order: 1,10,12,20
Vector Descending: 20,12,10,1
The organization of arrays is widely used in everyday life of a web developer as well as other features of the language, so to understand the function of each is essential.
Want to test this and other code in Javascript? So now download our web development tool and learn not only that, but over all the resources we provide to make your day to day as a programmer much easier. Do not waste time and download now the free version of Scriptcase and enjoy!]
I hope you enjoyed these tips. Follow our blog and stay on top of all the news.
You might also like…