Becky Becky - 7 months ago 11
Javascript Question

Shift final given number of elemts to front of array

I've got an array

var itemsArr = ["blue", "wine", "orange", "yellow", "cyan"];


How can I get a certain amount of array elements from the END to the FRONT of the array?

Expected output:

example 1:

//shift final 3 elements
var expected = ["orange", "yellow", "cyan", "blue", "wine"];


example 2:

//shift final 2 elements
var expected = ["yellow", "cyan", "blue", "wine", "orange"];

Answer

You can use a combination with Array#splice and Array#concat.

var itemsArr = ["blue", "wine", "orange", "yellow", "cyan"];

itemsArr = itemsArr.splice(-3).concat(itemsArr);
document.write('<pre>' + JSON.stringify(itemsArr, 0, 4) + '</pre>');

itemsArr = itemsArr.splice(3).concat(itemsArr);
document.write('<pre>' + JSON.stringify(itemsArr, 0, 4) + '</pre>');