To rotate elements in an array using TypeScript, you can implement a custom rotation function that shifts elements by a specified number of positions.
In this example,
intArray
containing integers.rotate
function that shifts elements by a specified number of positions.function rotateArray(array: number[], positions: number): number[] {
const n = array.length;
positions %= n;
reverseArray(array, 0, n - 1);
reverseArray(array, 0, positions - 1);
reverseArray(array, positions, n - 1);
return array;
}
function reverseArray(array: number[], start: number, end: number): void {
while (start < end) {
const temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
const intArray: number[] = [1, 2, 3, 4, 5];
console.log('Rotated Array:', rotateArray(intArray, 2));
Rotated Array: [ 4, 5, 1, 2, 3 ]
In this example,
strArray
containing strings.rotate
function that shifts elements by a specified number of positions.function rotateArray(array: string[], positions: number): string[] {
const n = array.length;
positions %= n;
reverseArray(array, 0, n - 1);
reverseArray(array, 0, positions - 1);
reverseArray(array, positions, n - 1);
return array;
}
function reverseArray(array: string[], start: number, end: number): void {
while (start < end) {
const temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
const strArray: string[] = ['apple', 'banana', 'cherry', 'date', 'fig'];
console.log('Rotated Array:', rotateArray(strArray, 3));
Rotated Array: [ 'cherry', 'date', 'fig', 'apple', 'banana' ]
In this tutorial, we learned How to Rotate Elements in an Array in TypeScript language with well detailed examples.