First Reverse Try
Description
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]
.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] array.integer arr
A positive integer.
Guaranteed constraints:
0 \leq arr.length \leq 50
,
-10^4 \leq arr[i] \leq 10^4
. -
[output] array.integer
- Array
arr
with its first and its last elements swapped.
- Array
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
function firstReverseTry(arr) {
if (arr.length < 2) return arr;
var first = arr.shift();
var last = arr.pop();
return [last, ...arr, first];
}