-1

I have an array with 8 elements. How do I move the last 4 elements to the front?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Danyerden
  • 17
  • 2

3 Answers3

3

You can use Array.prototype.concat() combined with Array.prototype.slice():

const arr = [1, 2, 3, 4, 5, 6, 7, 8]
const result = arr.slice(4).concat(arr.slice(0, 4))

console.log(result)

A more dynamic version:

const arr = [1, 2, 3, 4, 5, 6, 7, 8]
const half = arr.length / 2 
const result = arr.slice(half).concat(arr.slice(0, half))

console.log(result)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
3

You can use a combination of the Array.prototype.slice method and the Spread operator.

First spread the last four elements from the original array and then spread the remaining elements from the beginning.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  newArr = [...arr.slice(-4), ...arr.slice(0, -4)];

console.log(newArr);

You can also do it by just using Array.prototype.Splice but remember it mutates the original array.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.splice(0, 0, ...arr.splice(-4));

console.log(arr);
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
2

If you're ok mutating the array (rather than creating a new one) splice the last four elements, and then unshift them to the start of the array.

(Note: splice returns an array, so you need to spread the elements out.)

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
arr.unshift(...arr.splice(-4));
console.log(arr);
Andy
  • 61,948
  • 13
  • 68
  • 95