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.
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.
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the 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.
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"]
You can slice the array and then join it in reversed order:
var array2 = array1.slice(3).concat(array1.slice(0, 3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With