Javascript Array rotateArray(n)

Description

Javascript Array rotateArray(n)


/* Rotating an Array by N-Pos
** By Patrick Adeyemi//from  w w w . ja v a2  s.  c  o  m
*/

Array.prototype.rotateArray = function(n){
 var newArray  = [];
 var l = this.length;
 
 for(var i=0; i < l; i++){
  newArray[(i+n) % l] = this[i];
 }
 return newArray;
}

var y = [];
var n = 3;
var x = [1, 2, 3, 4, 5, 6];
y = x.rotateArray(n);
document.writeln("<h1>Result Page for Rotating an Array</h1>");
document.writeln("Array Input: [" + x.join(',') + "]<br /><br />");
document.writeln("Array Output by " + n + " Position: <br />[" + y.join(',') + "]<br /><br />");



PreviousNext

Related