Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to move an array element from one array position to another...

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

In JavaScript, we can access an array element as in other programming languages like C, C++, Java etc. Also, there is a method called splice() in JavaScript, by which an array can be removed or replaced by another element for an index. So to move an array element from one array position to another we can splice() method or we can simply use array indexing ([]). 
 

Example 1: Simple code for moving an array element from one array position to another, without using any functions. 

javascript




let arr = ["C++", "Java", "JS", "Python"];
 
console.log("Original array: " + arr);
 
// Position where from the element is
// going to move here 'python' is moved
let x = 3;
 
// Position at which element is to be
// moved here 'python' is moved to 
// index 1 which is index of 'Java'
let pos = 1;
 
// Store the moved element in a temp
// variable
let temp = arr[x];
 
// shift elements forward
let i;
for (i = x; i >= pos; i--) {
    arr[i] = arr[i - 1];
}
 
// Insert moved element at position 
arr[pos] = temp;
 
console.log("After move: " + arr);


Output

Original array: C++,Java,JS,Python
After move: C++,Python,Java,JS

Example 2: Now move an array element from one array position to another using a function. 

javascript




let arr = ["C++ ", "Java ", "JS ",
    "Ruby ", "Python "];
 
//     Print the array before moving
console.log("Original array: " + arr);
 
// Position where from the element is
// going to move here 'Ruby' is moved
let moveEle = 3;
 
// Position at which element is to be moved
// here 'Ruby' is moved to  index 1 which is
// index of 'Java'
let moveToIndx = 1;
 
// If actual index of moved element is
// less than 0 when 'moveEle += array size'
while (moveEle < 0) {
    moveEle += arr.length;
}
 
// Where the element to be moved f that
// index is less than 0 when
// 'moveToIndx += array size'
while (moveToIndx < 0) {
    moveToIndx = moveToIndx + arr.length;
}
 
// If 'moveToIndx' is greater than the
// size of the array then with need to
// push 'undefined' in the array.
if (moveToIndx >= arr.length) {
    let un = moveToIndx - arr.length + 1;
    while (un--) {
        arr.push(undefined);
    }
}
// Here element of 'moveEle' is removed and
// pushed at 'moveToIndx' index
arr.splice(moveToIndx, 0, arr.splice(moveEle, 1));
 
// Print the array after moving
console.log("After move: " + arr);


Output

Original array: C++ ,Java ,JS ,Ruby ,Python 
After move: C++ ,Ruby ,Java ,JS ,Python 

Example 3: In this example, we will use slice(), concat(), and spread operator.

Javascript




const arr = [1, 2, 8, 4, 5];
const toMove = arr[2];
 
const newArr = [
  ...arr.slice(0, 2),
  ...arr.slice(3),
     toMove
];
console.log(newArr);


Output

[ 1, 2, 4, 5, 8 ]

RELATED ARTICLES

Most Popular

Recent Comments