Js: Reverse An Array But Reverse The Original Array Only --> Error: Running With No Output
I have following problem: // Reverse Array Write a function that accepts an array and reverses that array in place. The behavior should mimic the behavior of the native .reverse()
Solution 1:
Not sure why you need the unshift
you can just iterate and return the array where you are pushing the value
let myArray = [1, 2, 3, 4];
functionreverse(myArray) {
let newArray = [];
for (i = myArray.length - 1; i >= 0; i--) {
newArray.push(myArray[i])
}
return newArray;
}
console.log(reverse(myArray))
Solution 2:
You can iterate the array 'till the middle, and switch between the current (i
) and the opposite (length - i - 1
):
const myArray = [1, 2, 3, 4];
functionreverse(myArray) {
const length = myArray.length;
const middle = Math.floor(length / 2);
for(let i = 0; i < middle; i++) {
let tmp = myArray[i];
myArray[i] = myArray[length - i - 1];
myArray[length - i - 1] = tmp;
}
}
reverse(myArray);
console.log(myArray) // expected output is [4, 3, 2, 1]
Solution 3:
You can swap first and last element in an array and iteratively swap the next and prev respectively.
You don't have to visit the complete set in the loop, get the middle element and rotate the index around that
functionreverseInArray(arr){
let len = arr.length;
let temp;
for(let i=0; i < len/2; i++){
temp = arr[i];
arr[i] = arr[len - i - 1];
arr[len - i - 1] = temp;
}
return arr;
}
console.log(reverseInArray([1,2,3,4,5]));
Solution 4:
You could swap the first and the last element and start from the most inner item.
functionreverse(array) {
var i = array.length >> 1, // take half of the length as integer
l = array.length - 1; // last index value to calculate the other sidewhile (i--) [array[i], array[l - i]] = [array[l - i], array[i]];
}
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
reverse(a);
console.log(...a);
Solution 5:
Just swap pairs starting at either end of the array, until there's none left:
functionreverse(a) {
for (let i = 0, j = a.length - 1; i < j; ++i, --j) {
let tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a; // not required, but allows use in an expression
}
In ES2016 you can use destructuring assignments to perform the swap in one operation without the use of a temporary variable:
functionreverse(a) {
for (let i = 0, j = a.length - 1; i < j; ++i, --j) {
[ a[j], a[i] ] = [ a[i], a[j] ];
}
return a;
}
Post a Comment for "Js: Reverse An Array But Reverse The Original Array Only --> Error: Running With No Output"