467,118 Members | 916 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,118 developers. It's quick & easy.

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

Which built-in method reverses the order of the elements of an array?
May 22 '19 #1
  • viewed: 2461
Share:
4 Replies
gits
Expert Mod 4TB
there is an Array method called: reverse
May 22 '19 #2
64KB
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
128KB
> 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 4TB
"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.

Similar topics

2 posts views Thread by Steve Richter | last post: by
2 posts views Thread by Klaudiusz Bryja | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.