1function arrayMove(arr, fromIndex, toIndex) {
2 var element = arr[fromIndex];
3 arr.splice(fromIndex, 1);
4 arr.splice(toIndex, 0, element);
5}
6
1// Move element '3' to where currently '1' is
2const numbers = [ 1, 2, 3, 4, 5 ]
3const numbersOriginal = Object.assign(numbers)
4const sourceIndex = 2
5const targetIndex = 0
6numbers.splice(targetIndex, 0, numbers.splice(sourceIndex, 1)[0])
7console.log(numbersOriginal)
8console.log(numbers)
1function moveElement(array,initialIndex,finalIndex) {
2 array.splice(finalIndex,0,array.splice(initialIndex,1)[0])
3 console.log(array);
4 return array;
5}
6// Coded By Bilal
1function moveArrayItemToNewIndex(arr, old_index, new_index) {
2 if (new_index >= arr.length) {
3 var k = new_index - arr.length + 1;
4 while (k--) {
5 arr.push(undefined);
6 }
7 }
8 arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
9 return arr;
10};
11
12//move index 1(b) to index 2(c)
13console.log(moveArrayItemToNewIndex(["a","b","c","d"], 1, 2)); // returns ["a", "c", "b", "d"]