how to change index of array element in javascript code example
Example 1: change index array javascript
Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
Example 2: 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 3: javascript move item in array to another index
function moveArrayItemToNewIndex(arr, old_index, new_index) {
if (new_index >= arr.length) {
var k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr;
};
console.log(moveArrayItemToNewIndex(["a","b","c","d"], 1, 2));