Skip to main content
added 66 characters in body
Source Link
Andy
  • 63.6k
  • 13
  • 72
  • 99

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 that

(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);

splice the last four elements, and then unshift them to the start of the array. Note that 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);

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);

added 172 characters in body
Source Link
Andy
  • 63.6k
  • 13
  • 72
  • 99

splice the last four elements, and then unshift them to the start of the array. Note that 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);

splice the last four elements, and then unshift them to the start of the array.

const arr = [1, 2, 3, 4, 5, 6, 7, 8]; arr.unshift(...arr.splice(-4)); console.log(arr);

splice the last four elements, and then unshift them to the start of the array. Note that 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);

Source Link
Andy
  • 63.6k
  • 13
  • 72
  • 99

splice the last four elements, and then unshift them to the start of the array.

const arr = [1, 2, 3, 4, 5, 6, 7, 8]; arr.unshift(...arr.splice(-4)); console.log(arr);