How do I shift an array of items up by 4 places in Javascript

Darryl Hebbes picture Darryl Hebbes · Oct 5, 2009 · Viewed 12.2k times · Source

How do I shift an array of items up by 4 places in Javascript?

I have the following string array:

var array1 = ["t0","t1","t2","t3","t4","t5"];

I need a function convert "array1" to result in:

// Note how "t0" moves to the fourth position for example
var array2 = ["t3","t4","t5","t0","t1","t2"];  

Thanks in advance.

Answer

Russ Cam picture Russ Cam · Oct 5, 2009
array1 = array1.concat(array1.splice(0,3));

run the following in Firebug to verify

var array1 = ["t0","t1","t2","t3","t4","t5"];
console.log(array1);
array1 = array1.concat(array1.splice(0,3));
console.log(array1);

results in

["t0", "t1", "t2", "t3", "t4", "t5"]
["t3", "t4", "t5", "t0", "t1", "t2"]