By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,061 Members | 1,222 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,061 IT Pros & Developers. It's quick & easy.

Which built-in method reverses the order of the elements of an array?

P: 22
Which built-in method reverses the order of the elements of an array?
May 22 '19 #1
Share this Question
Share on Google+
4 Replies


gits
Expert Mod 5K+
P: 5,387
there is an Array method called: reverse
May 22 '19 #2

P: 37
You can use revese method of javascript

example : array_name.reverse();

you can try below code:

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h3>Click the button to reverse the order of the elements in the array.</h3>
  6.  
  7. <button onclick="myFunction()">Try it</button>
  8.  
  9. <p id="demo"></p>
  10. <script>
  11. var cricketers = ["virat", "Rohit", "hardik", "Rahul"];
  12. document.getElementById("demo").innerHTML = cricketers;
  13.  
  14. function myFunction() {
  15.     cricketers.reverse();
  16.   document.getElementById("demo").innerHTML = cricketers;
  17. }
  18. </script>
  19.  
  20. </body>
  21. </html>
  22.  
  23.  
Feb 20 '20 #3

100+
P: 112
> var a = [1, 2, 3]
undefined
> a
[1, 2, 3]
> a.reverse();
[3, 2, 1]
> a
[3, 2, 1]
> a.slice().reverse();
[1, 2, 3]
> a
[3, 2, 1]

"a.reverse();" : Replace the array
"a.slice().reverse();" : Display only without replace the array
Feb 20 '20 #4

gits
Expert Mod 5K+
P: 5,387
"a.reverse();" : Replace the array
"a.slice().reverse();" : Display only without replace the array
more accurate would be:

a.reverse(); - mutates the array a
a.slice().reverse(); - mutates a new array that was returned by the slice method - so the original array a would stay unmodified
Feb 20 '20 #5

Post your reply

Sign in to post your reply or Sign up for a free account.