How to move element to first position in array with JavaScript?

Sometimes, we want to move element to first position in array with JavaScript.

In this article, we’ll look at how to move element to first position in array with JavaScript.

How to move element to first position in array with JavaScript?

To move element to first position in array with JavaScript, we can use the spread operator and the array slice method.

For instance, we write:

const data = [{
    id: 1,
    age: 24,
    gender: "male"
  },
  {
    id: 2,
    age: 27,
    gender: "female"
  },
  {
    id: 3,
    age: 30,
    gender: "male"
  },
  {
    id: 4,
    age: 10,
    gender: "female"
  },
]
const newData = [...data.slice(3), ...data.slice(0, 3)]
console.log(newData)

We call data.slice to get the last element and the first 3 elements respectively.

Then we spread each array into a new array to populate the values of the returned arrays in the new array.

As a result, we get:

[
  {
    "id": 4,
    "age": 10,
    "gender": "female"
  },
  {
    "id": 1,
    "age": 24,
    "gender": "male"
  },
  {
    "id": 2,
    "age": 27,
    "gender": "female"
  },
  {
    "id": 3,
    "age": 30,
    "gender": "male"
  }
]

for newData.

Conclusion

To move element to first position in array with JavaScript, we can use the spread operator and the array slice method.