Categories
JavaScript Answers

How to move an array element from one array position to another with JavaScript?

Spread the love

To move an array element from one array position to another with JavaScript, we use the splice method.

For instance, we write

const arrayMove = (arr, fromIndex, toIndex) => {
  const element = arr[fromIndex];
  arr.splice(fromIndex, 1);
  arr.splice(toIndex, 0, element);
};

to define the arrayMove method.

We get the element at fromIndex with arr[fromIndex].

Then we call arr.splice with fromIndex and 1 to remove the item at fromIndex.

Then we insert the element at toIndex by calling splice with toIndex, 0, and element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *