Change the Position of an Array Element in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Change the Position of an Element in an Array #

To change the position of an element in an array:

  1. Use the splice() method to remove the element at the specific index from the array.
  2. Use the splice() method to insert the element at the new index in the array.
  3. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.
index.js
const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; const element = arr.splice(fromIndex, 1)[0]; console.log(element); // ['css'] arr.splice(toIndex, 0, element); console.log(arr); // 👉️ ['js', 'ts', 'css']

We changed the position of the array element with value css from index 0 to index 2.

We first used the Array.indexOf method to get the index of the element.

Then we used the Array.splice method, passing it the following 2 arguments:

  1. start index - the index at which to start changing the array
  2. delete count - how many elements should be deleted from the array
We only want to delete a single element so we set the delete count argument to 1.

The splice method returns an array containing the removed elements.

index.js
const arr = ['css', 'js', 'ts']; const splice = arr.splice(0, 1); console.log(splice) // 👉️ ['css']

Since we know that we only deleted 1 element from the array, we directly access the array element at index 0 to get the value of the element we will insert at the new position.

The last step is to call the splice method again. However, this time we use it to add an element to the array at a specific index.

The 3rd argument we passed to the splice method is the element to add to the array.

We set the start index argument to the new position the element should be placed in.

Lastly, we set the delete count argument to 0 to denote that we don't want to remove any elements from the array.

In this article we used the splice method to:

  • remove an element at a specific index from an array and get its value
  • add an element to an array at a specific index
Personally, I would have liked to have 2 separate built in methods to achieve these 2 very different goals. However, this is the way to do it in JavaScript.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.