Skip to content

Instantly share code, notes, and snippets.

@moimikey
Last active June 14, 2023 17:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/8f3c95865829f9e17081 to your computer and use it in GitHub Desktop.
Save moimikey/8f3c95865829f9e17081 to your computer and use it in GitHub Desktop.
reversing an array, the fast and simple way!
var i, arr = [1, 2, 3, 4, 5, 6, 7, 8];
for(i = 0; i < arr.length / 2; i++) {
var temp = arr[i];
arr[i] = arr[arr.length - i - 1]
arr[arr.length - i - 1] = tmp
}
/*
passes:
[1,2,3,4,5,6,7,8]
[8,2,3,4,5,6,7,8]
[8,2,3,4,5,6,7,1]
[8,7,3,4,5,6,7,1]
[8,7,3,4,5,6,2,1]
[8,7,6,4,5,6,2,1]
[8,7,6,4,5,3,2,1]
[8,7,6,5,5,3,2,1]
[8,7,6,5,5,3,2,1]
[8,7,6,5,4,3,2,1]
slow mo:
http://toolness.github.io/slowmo-js/?code=var%20arr%20%3D%20%5B1%2C%202%2C%203%2C%204%2C%205%2C%206%2C%207%2C%208%5D%3B%0Afor(var%20i%20%3D%200%3B%20i%20%3C%20arr.length%20%2F%202%3B%20i%2B%2B)%20%7B%0A%20%20var%20temp%20%3D%20arr%5Bi%5D%3B%0A%20%20arr%5Bi%5D%20%3D%20arr%5Barr.length%20-%20i%20-%201%5D%0A%20%20arr%5Barr.length%20-%20i%20-%201%5D%20%3D%20tmp%0A%7D&filterrange=0-0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment