Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to move specified number of elements to the end of an array in JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




<script>
    function moveElementsToEndOfArray(arr, x) {
     
        // arr is the input array
        // x is the no. of elements that
        // needs to be moved to end of
        // the array
     
        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);
</script>

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




<script>
    function moveElementsToEndOfArray(arr, x) {
     
        // Array is [1, 2, 3, 4, 5] and x = 2
        // final output would be [3, 4, 5, 1, 2]
        x = x % (arr.length);
     
        for (let i = 0; i < x; i++) {
            arr.push(arr[i]);
        }
     
        // After this loop array will
        // be [1, 2, 3, 4, 5, 1, 2]
        arr.splice(0, x);
     
        // Splice method will remove first
        // x = 2 elements from the array
        // so array will be [3, 4, 5, 1, 2]
     
        console.log(arr);
    }
     
    let arr = [1, 2, 3, 4, 5];
    let k = 2;
    moveElementsToEndOfArray(arr, k);
</script>

Output:

[ 3, 4, 5, 1, 2 ]

My Personal Notes arrow_drop_up
Last Updated : 14 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials