How to use Array Slice and Concatenation Method In Javascript

This approach involves slicing the array into two parts based on the rotation index and then concatenating them in the desired order. This method first calculates the rotation index, then slices the array accordingly, and concatenates the parts in the rotated order.

Syntax:

  // Create the rotated array by concatenating two slices
const rotatedArray = arr.slice(rotateBy).concat(arr.slice(0, rotateBy));

// Return the rotated array
return rotatedArray;

Example: TypeScript Array Rotation: Left Rotate by 2 Positions – Demonstrating a function to rotate an array leftward by a specified number of positions.

Javascript




function rotateArray(arr, rotateBy) {
    const n = arr.length;
    rotateBy %= n;
 
    return arr.slice(rotateBy).concat(arr.slice(0, rotateBy));
}
 
const originalArray = [1, 2, 3, 4, 5];
const rotatedArray = rotateArray(originalArray, 2);
console.log(rotatedArray);


Output

[ 3, 4, 5, 1, 2 ]

JavaScript Program for array rotation

Array rotation in JavaScript involves shifting elements within an array to the left or right by a specified number of positions.

There are several approaches to rotate an array in JavaScript which are as follows:

Table of Content

  • Using Array Slice and Concatenation Method
  • Using Array Splice and Push method
  • Using Array Reversal

Similar Reads

Using Array Slice and Concatenation Method

This approach involves slicing the array into two parts based on the rotation index and then concatenating them in the desired order. This method first calculates the rotation index, then slices the array accordingly, and concatenates the parts in the rotated order....

Using the Array Splice and Push method

...

Using Array Reversal

This approach involves using the splice() method to remove elements from the beginning of the array and then push them to the end. Here, we first remove the elements to be rotated from the beginning of the array using splice() and then push them to the end using the spread operator (…)....

Contact Us