In JavaScript, elements from the beginning of an array can be moved to the end to rotate the array.
- The number of elements to move can be specified using a variable.
- The original array can either be modified or a new array can be created.
- slice() and the spread (...) operator can be used to create a rotated array.
- push(), shift(), and splice() can be used to modify the original array.
Example:
Input:
arr = [1, 2, 3, 4, 5]
X = 2
Output:
[3, 4, 5, 1, 2]
Approach 1: Using slice() and Spread Operator
In this approach, the slice() method is used to divide the array into two parts. The first X elements are extracted separately, and the remaining elements are placed before them using the spread (...) operator.
Example: Moves the first 5 elements to the end of the array.
function moveElementsToEndOfArray(arr, x) {
let n = arr.length;
// Handle values greater than array length
x = x % n;
// Extract the first x elements
let firstXElements = arr.slice(0, x);
// Extract the remaining elements
let remainingElements = arr.slice(x, n);
// Move the first x elements to the end
return [...remainingElements, ...firstXElements];
}
let arr = [1, 2, 3, 4, 5, 6];
let k = 5;
console.log(moveElementsToEndOfArray(arr, k));
Output
[ 6, 1, 2, 3, 4, 5 ]
Approach 2: Using for Loop and splice()
In this approach, a for loop is used to append the first X elements to the end of the array. The splice() method then removes those elements from the beginning.
Example: Moves the first 2 elements to the end of the array.
function moveElementsToEndOfArray(arr, x) {
x = x % arr.length;
// Append the first x elements to the end
for (let i = 0; i < x; i++) {
arr.push(arr[i]);
}
// Remove the first x elements
arr.splice(0, x);
return arr;
}
let arr = [1, 2, 3, 4, 5];
let k = 2;
console.log(moveElementsToEndOfArray(arr, k));
Output
[ 3, 4, 5, 1, 2 ]
Approach 3: Using push() and shift() in a Loop
In this approach, the shift() method removes the first element from the array, while push() adds that element to the end. Repeating this process rotates the array by the specified number of positions.
Example: This example moves the first 2 elements to the end of the array.
function moveElementsToEndWithLoop(arr, count) {
count = count % arr.length;
for (let i = 0; i < count; i++) {
arr.push(arr.shift());
}
return arr;
}
const array = [1, 2, 3, 4, 5];
console.log(moveElementsToEndWithLoop(array, 2));
Output
[ 3, 4, 5, 1, 2 ]
Approach 4: Using slice() and Spread Operator in a Single Expression
In this approach, the slice() method divides the array into two parts. The spread operator then combines the remaining elements with the first X elements.
Syntax:
const result = [...array.slice(X), ...array.slice(0, X)];Example: Moves the first 2 elements to the end of the array.
const arr = [1, 2, 3, 4, 5];
const X = 2;
const result = [...arr.slice(X), ...arr.slice(0, X)];
console.log(result); // Output: [3, 4, 5, 1, 2]
Output
[ 3, 4, 5, 1, 2 ]