views:

185

answers:

5

Hi, 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.

+7  A: 

You can slice the array and then join it in reversed order:

var array2 = array1.slice(3).concat(array1.slice(0, 3));
Lukáš Lalinský
This is nice and concise. If you're going to do this frequently, and need to shift it by different amounts, you could put this into a function and pass in a variable to plug in where the 3 is. (I use the word "shift" hesitantly, since that's a Javascript array method, too.)
Nathan Long
+2  A: 

One more way would be this:

var array2 = array1.slice(0);

for (var i = 0; i < 3; i++) {
    array2.push(array2.shift());
}
Reinis I.
+10  A: 
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"]
Russ Cam
Oh, very nice. :)
Nathan Long
as a function- `function reorderArray(arr, startIndex, howMany) { return arr.concat(arr.splice(startIndex,howMany)); }` would need error checking as well :)
Russ Cam
+1  A: 
function shiftArray(theArray, times) {
    // roll over when longer than length
    times = times % theArray.length;
    var newArray = theArray.slice(times);
    newArray = newArray.concat(theArray.slice(0, times));
    return newArray;
}

var array1 = ["t0","t1","t2","t3","t4","t5"];
var array2 = shiftArray(array1, 3);
alert(array2); // ["t3","t4","t5","t0","t1","t2"]
Georg
A: 

Another way - paste the following code into the large Firebug console to confirm it works:

var a = [0, 1, 2, 3, 4, 5];
for (var i = 0; i < 3; i++) {
    a.unshift(a.pop());
}
// the next line is to show it in the Firebug console; variable "a" holds the array
a.toString(",");
NickFitz
The end result should be an array, not a string, right?
Nathan Long
@Nathan: the end result *is* an array, held in the variable "a"; the line outputting it as a string is for illustrative purposes, which is why it's not assigned to anything (it goes straight to the console in Firebug). I'll correct my answer to make it clear that I meant the Firebug console... sometimes I forget it's not built-in to the browser ;-)
NickFitz