Sun Oct 10 2021·2 min read
Photo by Brooke Cagle
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.
splicemethod 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); 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
0 to index
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:
We only want to delete a single element so we specify a delete count of
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.
splicemethod 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:
I'll send you 1 email a week with links to all of the articles I've written that week