-1

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

3
  • 2
    What have you tried so far? Commented May 10, 2022 at 9:17
  • I have tried using splice. But It is a bit confusing, also tried to use pushing new items and then unshifting them, but only 1 element moves to the start, no idea how to move more than one. (I am currently learning about Arrays so no prior knowledge). Commented May 10, 2022 at 9:19
  • 1
    Both slice and splice can move more than one item at a time Commented May 10, 2022 at 9:20

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

5 Comments

i was just wondering why you used concat instead of the spread operator.... the concat method is much better performance wise. see stackoverflow.com/questions/48865710/…. Good job :)
For performance
@CraigWayne Thank you for your comment.. Checking on the link
Found this very helpful, now I understand how to move things around. Appreciated!
@Danyerden Good to help
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);

Comments

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

3 Comments

This solution mutates arr
I'm ok with that.
This is nice +1, I came up with arr.splice(0, 0, ...arr.splice(-4))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.