In this lesson we study JavaScript reverse method, which is useful for reversing the elements of an array.
The syntax is as follows: array.reverse().
So let’s take some examples to understand how it works.
JavaScript reverse – first example
Reverse the order of an array of strings taken as input, using the reverse() method.
So let’s take our array as input, for example an array made up of school objects like the following:
var objectsSchool = ['eraser', 'notebook', 'pencil'];
Then we simply use the reverse method on the given array, following its syntax and view the result in the browser console.
Here is the example code for using the reverse() method of JavaScript:
objectsSchool.reverse();
console.log(objectsSchool);
In this way, in the console we will see the contents of the starting array in reverse order.
JavaScript reverse – second example
Sort an array of numbers and then reverse it using the reverse() method.
So this time we take an array of numbers as input, as shown in the example below:
var numerbs = [5,4,3,2,6,9,62];
We also remember that in order to perform a numerical sorting of an array we must use the syntax array.sort(comparison function), as explained in this lesson: sort javascript.
Then we order it following the specifications indicated in the previous lesson:
numerbs.sort(function(a, b) {
return a - b;
});
Finally we apply the reverse method of JavaScript and display the result, for convenience, in the console of our browser.
numerbs.reverse();
console.log(numerbs);
If we reflect in this case, the same result could be obtained simply by performing a descending ordering of the starting array.
Below I therefore present a possible alternative solution to the proposed algorithm that does not use the reverse method of JavaScript.
var numbers = [5,4,3,2,6,9,62];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers);
Conclusion
In this lesson we have simply seen some very simple examples of using the JavaScript reverse method. In the next lessons we will face still other methods, through the study of practical examples.