0

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

JavaScript
function array_move(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; // for testing
};

console.log(array_move([1, 2, 3], 0, 1)); // returns [2, 1, 3] - move item from position 0 to position 1

console.log(array_move([1, 2, 3, 4, 5, 6, 7, 8, 9], 1, 5)); // returns [1, 3, 4, 5, 6, 2, 7, 8, 9]
RUN
add comment
Suggest a different solution or add another example