Javascript Array Reverse an array 2

Description

Javascript Array Reverse an array 2

///Option 1: reverse array by pushing contents into a new array

function reverse_array(array)
{
  var new_array = [];
  for(var i = array.length-1; i > -1; i--)
    {// w  w w. j  av  a 2  s. co  m
      new_array.push(array[i]);
    }
  return new_array;
}
console.log(reverse_array([1,2,3,4]));

//Option 2: divide array in half and reverse array from each index - i - 1

function reverse_array(array)
{
  for(var i = 0; i < array.length/2; i++)
    {
      var temp = array[i];
      array[i] = array[array.length-1 - i];
      array[array.length-1-i] = temp;
    }
  return array;
}
console.log(reverse_array([1,2,3,4]));



PreviousNext

Related