Change the Position of an Array Element in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20212 min read

banner

Photo by Brooke Cagle

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']

In the code snippet we change the position of the array element with value css from index 0 to index 2.

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

Then we use the Array.splice method, passing it the following 2 parameters:

  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 specify a delete count of 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 parameter we passed to the splice method is the element to add to the array.

For our start index we specify the new position the element should be placed in.

We set the delete count parameter 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee