move elements in array, javascript code example
Example 1: how to move an element of an array in javascript
function moveElement(array,initialIndex,finalIndex) {
array.splice(finalIndex,0,array.splice(initialIndex,1)[0])
console.log(array);
return array;
}
Example 2: javascript move element in array
function arrayMove(arr, fromIndex, toIndex) {
var element = arr[fromIndex];
arr.splice(fromIndex, 1);
arr.splice(toIndex, 0, element);
}
Example 3: javascript array move element
const numbers = [ 1, 2, 3, 4, 5 ]
const numbersOriginal = Object.assign(numbers)
const sourceIndex = 2
const targetIndex = 0
numbers.splice(targetIndex, 0, numbers.splice(sourceIndex, 1)[0])
console.log(numbersOriginal)
console.log(numbers)