Example:
Input : arr[] = [1, 2, 3] Output : arr[] = [3, 2, 1]
Solution-1:
function reverseArray(arr) { let tempArr = []; // loop from backwards and store array value // in a new temporary array and return temp arr for(let i=arr.length-1; i >= 0; i--) { tempArr.push(arr[i]); } return tempArr; } console.log(reverseArray([1, 2, 3, 4, 5]));
Solution-2:
function reverseArray(arr) { let start = 0; // first index in the array let end = arr.length-1; // last index in the array while(start < end) { // get first element in temp var let temp = arr[start]; // replace first value with last value arr[start] = arr[end]; // replace last value with first value arr[end] = temp; // increment start to next item start++; // decrement end to previous item end--; } return arr; } console.log(reverseArray([1, 2, 3, 4, 5]));