w3resource

JavaScript: Move an array element from one position to another

JavaScript Array: Exercise-38 with Solution

Write a JavaScript function to move an array element from one position to another.

Test Data:
console.log(move([10, 20, 30, 40, 50], 0, 2));
[20, 30, 10, 40, 50]
console.log(move([10, 20, 30, 40, 50], -1, -2));
[10, 20, 30, 50, 40]

Pictorial Presentation:

JavaScript: Move an array element from one position to another

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to move an array element from one position to another.</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function move(arr, old_index, new_index) {
    while (old_index < 0) {
        old_index += arr.length;
    }
    while (new_index < 0) {
        new_index += arr.length;
    }
    if (new_index >= arr.length) {
        var k = new_index - arr.length;
        while ((k--) + 1) {
            arr.push(undefined);
        }
    }
     arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);  
   return arr;
}

console.log(move([10, 20, 30, 40, 50], 0, 2));

console.log(move([10, 20, 30, 40, 50], -1, -2));

Sample Output:

[20,30,10,40,50]
[10,20,30,50,40]

Flowchart:

Flowchart: JavaScript: Move an array element from one position to another

ES6 Version:

function move(arr, old_index, new_index) {
    while (old_index < 0) {
        old_index += arr.length;
    }
    while (new_index < 0) {
        new_index += arr.length;
    }
    if (new_index >= arr.length) {
        let k = new_index - arr.length;
        while ((k--) + 1) {
            arr.push(undefined);
        }
    }
     arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);  
   return arr;
}

console.log(move([10, 20, 30, 40, 50], 0, 2));

console.log(move([10, 20, 30, 40, 50], -1, -2));

Live Demo :

See the Pen JavaScript - Move an array element from one position to another-array-ex- 38 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to create a specified number of elements and pre-filled string value array.
Next: Write a JavaScript function to filter false, null, 0 and blank values from an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

Returns true if the given number is a power of 2, false otherwise

Example:

const tips_isPowerOfTwo = n => !!n && (n & (n - 1)) == 0;
console.log(tips_isPowerOfTwo(0)); 
console.log(tips_isPowerOfTwo(4));
console.log(tips_isPowerOfTwo(16));

Output:

false
true
true