Change The Position Of An Array Element In JavaScript

To change the position of an array element in JavaScript –

  1. Use the Array.splice() method to remove the element from a specific index.
  2. Use the Array.splice() method to add the element to another index.

Let’s discuss this method in detail below.

how to change the position of an array element in javascript

splice() To Change The Position Of An Array Element In JavaScript

The splice() method is used to change the position of an array element in JavaScript. It can be used to add or remove elements from an array. The syntax of the splice() method is as follows:

array.splice(index, howmany, item1, ….., itemX)

Index: specifies the position of where to add/remove items.

Howmany: specifies the number of items to be removed. If set to 0, no items will be removed.

Item1, …, itemX: optional. Specifies the new item(s) to be added to the array.

The following examples will help you understand the splice() method better.

Here is an example of how to change the position of an element from 0 to 2 in an array –

var arr = ['a', 'b', 'c'];

var element = arr.splice(0, 1)[0]; //'a' gets removed

console.log(arr); //['b','c']

arr.splice(2,0, element); //insert 'a' at index 2

console.log(arr); //['b','c', 'a']

As you can see, the first element in the array (i.e. ‘a’) is removed and then inserted at index 2.

Here is an example of how to move an element from index 3 to index 1 in an array –

var arr = ['a', 'b', 'c', 'd', 'e'];

var element = arr.splice(3, 1)[0]; //'d' gets removed

console.log(arr); //['a','b','c', 'e']

arr.splice(1, 0, element); //insert 'd' at index 1

console.log(arr); //['a','d','b','c', 'e']

As you can see, the element ‘d’ is first removed from index 3 and then inserted at index 1.

In the next example, let’s see how to move multiple elements from one position to another –

var arr = ['a', 'b', 'c', 'd', 'e'];

var elements = arr.splice(3, 2); //['d','e'] gets removed

console.log(arr); //['a','b','c']

arr.splice(1, 0, …elements); //insert ['d','e'] at index 1

console.log(arr); //['a','d','e', 'b','c']

In the above code, we use the spread operator to insert the removed elements at another position. The spread operator allows us to insert an array of elements as individual arguments.

You can also add new items while removing elements from an array –

var arr = ['a', 'b', 'c'];

arr.splice(1, 1, 'd', 'e'); //remove 1 element from index 1 and insert ['d','e']

console.log(arr); //['a', 'd', 'e', 'c']

In the above code, we remove one element from index 1 and insert two new elements (‘d’ and ‘e’) in its place.

NOTE: The splice() method changes the original array. It doesn’t create a new one.

Leave a Reply