Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To change the position of an element in an array:
splice()
method to remove the element at the specific index from
the array.splice()
method to insert the element at the new index in the
array.splice
method changes the original array by removing or replacing
existing elements, or adding new elements at a specific index.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
.The splice
method returns an array containing the removed elements.
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.
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: