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
// arr is the input array and x is the no. // of elements that needs to be moved to // end of the array function moveElementsToEndOfArray(arr, x) { let n = arr.length; // if x is greater than length // of the array x = x % n; let first_x_elements = arr.slice(0, x); let remaining_elements = arr.slice(x, n); // Destructuring to create the desired array arr = [...remaining_elements, ...first_x_elements]; console.log(arr); } let arr = [1, 2, 3, 4, 5, 6]; let k = 5; moveElementsToEndOfArray(arr, k); |
[ 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
// Array is [1, 2, 3, 4, 5] and x = 2 // final output would be [3, 4, 5, 1, 2] function moveElementsToEndOfArray(arr, x) { x = x % (arr.length); // After this loop array will // be [1, 2, 3, 4, 5, 1, 2] for (let i = 0; i < x; i++) { arr.push(arr[i]); } // Splice method will remove first // x = 2 elements from the array // so array will be [3, 4, 5, 1, 2] arr.splice(0, x); console.log(arr); } let arr = [1, 2, 3, 4, 5]; let k = 2; moveElementsToEndOfArray(arr, k); |
[ 3, 4, 5, 1, 2 ]