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
.