Skip to content

Instantly share code, notes, and snippets.

@Nicknyr
Created April 13, 2020 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nicknyr/62f80de815498fa62bce20782b747c3c to your computer and use it in GitHub Desktop.
Save Nicknyr/62f80de815498fa62bce20782b747c3c to your computer and use it in GitHub Desktop.
CodeSignal - First Reverse Try
/*
Reversing an array can be a tough task, especially for a novice programmer. Mary just started coding, so she would like to start with something basic at first. Instead of reversing the array entirely, she wants to swap just its first and last elements.
Given an array arr, swap its first and last elements and return the resulting array.
Example
For arr = [1, 2, 3, 4, 5], the output should be
firstReverseTry(arr) = [5, 2, 3, 4, 1].
*/
function firstReverseTry(arr) {
// Splice first element
let first = arr.splice(0, 1);
// Splice last element
let last = arr.splice(arr.length - 1, 1);
// Push first element onto end of array
arr.push(first);
// Unshift last element onto beginning of array
arr.unshift(last);
// Splice caused the array to contain the first and last element as sub arrays, use flat to flatted the array to a single array
return arr.flat();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment