I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can't think of any possible method, so if anybody knows how, please help.
38 Answers
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]));
Comments
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]
Comments
I also faced the same problem. Thank you for this question. I did the code like the below snippet. It works nicely. I used ES6.
const Array = ["a", "b", "c", "d"];
let revArray = [].concat(Array).reverse();
when I console.log it I got the output like below
console.log(revArray)
// output: ["d","c","b","a"]
1 Comment
SherylHohman
Why would you name your array
Array? It is easily confused with keywords, and capitalising the first letter of a regular variable, while possible, it's against all conventions/best practices. Reserve that notion for signaling classes, etc.This function will work with arrays that may have gaps between their indices.
function reverse( a ) {
var b = [], c = [] ;
a.forEach( function( v ) { b.push( v ) } ) ;
a.forEach( function( v, i ) { c[i] = b.pop() } ) ;
return c ;
}
var a= [] ; a[1] = 2 ; a[3] = 4 ; a[7] = 6 ; a[9] = 8 ;
a = reverse( a ) ;
var s = '' ;
a.forEach( function( v, i ) { s += 'a[' + i + '] = ' + v + ' ' } ) ;
console.log( s ) ;
// a[1] = 8 a[3] = 6 a[7] = 4 a[9] = 2
Comments
I just rewrote the haskell implementation to js.
const rev = (list, reversed) => {
if (list.length == 0) return reversed
reversed.unshift(list[0])
return rev(list.slice(1), reversed)
}
const reverse = (list) => rev(list, [])
1 Comment
Ry-
This implementation is seriously inefficient in JS, since arrays aren’t linked lists.