How to move specified number of elements to the end of an array in JavaScript ?
Last Updated :
23 Jun, 2023
The purpose of this article is to move some specified elements to the end of an array using JavaScript.
Given an array of length say N, move some specified amount of elements say X to the end of the given array.
Input:
arr = [1, 2, 3, 4, 5]
X = 2
Output: The following array should be the output as the first two numbers are moved to the end of the array.
[3, 4, 5, 1, 2]
Approach 1:
- First, we will extract first X elements from the array into a new array arr1.
- Then extract the last (N-X) elements from the array into a new array arr2.
- Then concatenate arr1 after arr2 to get the resulting array.
Example:
Javascript
function moveElementsToEndOfArray(arr, x) {
let n = arr.length;
x = x % n;
let first_x_elements = arr.slice(0, x);
let remaining_elements = arr.slice(x, n);
arr = [...remaining_elements, ...first_x_elements];
console.log(arr);
}
let arr = [1, 2, 3, 4, 5, 6];
let k = 5;
moveElementsToEndOfArray(arr, k);
|
Output
[ 6, 1, 2, 3, 4, 5 ]
Approach 2:
- Run a for loop from index i = 0 till X-1
- In each iteration take the element at the current index and append it at the end of the array.
- After the iteration is complete, use the JavaScript splice() method to remove the first X elements from the array to get the resultant array.
Example:
Javascript
function moveElementsToEndOfArray(arr, x) {
x = x % (arr.length);
for (let i = 0; i < x; i++) {
arr.push(arr[i]);
}
arr.splice(0, x);
console.log(arr);
}
let arr = [1, 2, 3, 4, 5];
let k = 2;
moveElementsToEndOfArray(arr, k);
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...