I am saving some data in order using array
s, and I want to add a function that the user can reverse the list. I can\'t think of any possible method, so if anybo
20 bytes
let reverse=a=>[...a].map(a.pop,a)
array.reverse()
Above will reverse your array but modifying the original. If you don't want to modify the original array then you can do this:
var arrayOne = [1,2,3,4,5];
var reverse = function(array){
var arrayOne = array
var array2 = [];
for (var i = arrayOne.length-1; i >= 0; i--){
array2.push(arrayOne[i])
}
return array2
}
reverse(arrayOne)
How about this?:
function reverse(arr) {
function doReverse(a, left, right) {
if (left >= right) {
return a;
}
const temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
return doReverse(a, left, right);
}
return doReverse(arr, 0, arr.length - 1);
}
console.log(reverse([1,2,3,4]));
https://jsfiddle.net/ygpnt593/8/
Using ES6 rest operator and arrow function.
const reverse = ([x, ...s]) => x ? [...reverse(s), x] : [];
reverse([1,2,3,4,5]) //[5, 4, 3, 2, 1]
Below is a solution with best space and time complexity
function reverse(arr){
let i = 0;
let j = arr.length-1;
while(i<j){
arr[j] = arr[j]+arr[i];
arr[i] = arr[j] - arr[i];
arr[j] = arr[j] - arr[i];
i++;
j--;
}
return arr;
}
var arr = [1,2,3,4,5,6,7,8,9]
reverse(arr);
output => [9,8,7,6,5,4,3,2,1]
The shortest reverse method I've seen is this one:
let reverse = a=>a.sort(a=>1)