Exercise - Arrays Reverse - SOLVED

by Ryan Morris

JavaScript

/**
 * Reversing an array
 (without Array.reverse())
 *
 * 1)
 * Create a function, reverseArray(arr), that expects a single array as an argument
 * It will return a new array, with all the values in reverse order
 */

function reverseArray(arr) {
 
    var reversedArr = [];
    
    for (var i=0; i<arr.length; i++) {
       reversedArr.unshift(arr[i]);   
    }
    
    return reversedArr;
    
}

console.log(reverseArray(["A", "B", "C"]));
// → ["C", "B", "A"];

/* 
 * 2)
 * Upgrade the reverseArray function so that when you pass a value 
 * that is not an array it will throw an exception
 */

function reverseArray(arr) {

    if (!Array.isArray(arr)) {
     throw new Error("Not an array");   
    }
    
    var reversedArr = [];
    
    for (var i=0; i<arr.length; i++) {
       reversedArr.unshift(arr[i]);   
    }
    
    return reversedArr;
    
}

//reverseArray(5);

/*
 * 3) Bonus
 * Create a new function, reverseArrayInPlace(arr)
 * which does the same but does NOT use two arrays during the reversal process. 
*/

function reverseArrayInPlace(arr) {
 
    var holder;
    
    // swap first and last, and so on
    for (var i=0; i<arr.length/2; i++) {
      holder = arr[i];
      arr[i] = arr[arr.length-i-1];
      arr[arr.length-i-1] = holder;
    }
    
    return arr;
    
}

console.log("In place", reverseArrayInPlace(["a", "b", "c", "d"]));