Created
March 12, 2023 05:09
-
-
Save pjcodesjs/9e3c7f6d53d517184d0724dcf67e7b5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using the splice() method: | |
const arr = [1, 2, 3, 4, 5]; | |
const rotations = 2; // number of times to rotate the array | |
for (let i = 0; i < rotations; i++) { | |
const element = arr.splice(0, 1)[0]; | |
arr.push(element); | |
} | |
console.log(arr); // Output: [3, 4, 5, 1, 2] | |
// Using the concat() method: | |
const arr = [1, 2, 3, 4, 5]; | |
const rotations = 2; // number of times to rotate the array | |
const rotatedArr = arr.concat(arr.splice(0, rotations)); | |
console.log(rotatedArr); // Output: [3, 4, 5, 1, 2] | |
// Using the slice() and concat() methods: | |
const arr = [1, 2, 3, 4, 5]; | |
const rotations = 2; // number of times to rotate the array | |
const rotatedArr = arr.slice(rotations).concat(arr.slice(0, rotations)); | |
console.log(rotatedArr); // Output: [3, 4, 5, 1, 2] | |
// Using the reverse() method: | |
const arr = [1, 2, 3, 4, 5]; | |
const rotations = 2; // number of times to rotate the array | |
arr.reverse(); | |
arr.splice(0, rotations); | |
arr.reverse(); | |
arr.push(...arr.splice(0, rotations)); | |
console.log(arr); // Output: [3, 4, 5, 1, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment