Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 234
Darryl Hebbes Avatar asked Oct 05 '09 16:10

Darryl Hebbes


People also ask

How do you manipulate an array of objects in JavaScript?

const arr1 = [ {id:'124',name:'qqq'}, {id:'589',name:'www'}, {id:'45',name:'eee'}, {id:'567',name:'rrr'} ]; const arr2 = [ {id:'124',name:'ttt'}, {id:'45',name:'yyy'} ]; We are required to write a JavaScript function that takes in two such objects.

What does the array shift () method do in JavaScript?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How do you move items in an array?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.


2 Answers

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"]
like image 95
Russ Cam Avatar answered Nov 16 '22 01:11

Russ Cam


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

var array2 = array1.slice(3).concat(array1.slice(0, 3));
like image 36
Lukáš Lalinský Avatar answered Nov 15 '22 23:11

Lukáš Lalinský