I want to get the reverse of this array, in this case ([4,3,2,1]). The problem is I can use no reverse or other shorcuts.
const ar = [1, 2, 3, 4]
const reverse = function (arr) {
let x = arr;
for(i=0; i<x.length;i++) {
x[x.length-i-1]=x[i];
}
return x;
};
const reversedArray = reverse(ar);
console.log(reversedArray);
I thought it must be working, however when I run I get [ 1, 2, 2, 1 ] as an output. Which is because when i=1 at the second index there is no longer 3. What can I do?
ar.reverse()comes to mind ?Array.prototype.reversex.length/2over two and swapx[i]andx[x.length-i-1]