While working on my final project for Flatiron School’s first phase, I found myself in need of a JavaScript function that takes in an array of any length as an argument, rotates the elements counterclockwise, and console.logs each iteration of the array.
Here’s a step by step guide to my thought process:
Step 1. Declare function with an array as its single parameter:
function rotateCounterClockwise(array){
};
Step 2. Within the function, write a for-loop to iterate through the array based on its length:
function rotateCounterClockwise(array){
for (let i = 0; i < array.length; i++){
};
};
Step 3. Within the body of the for-loop, console.log the array so that each iteration is logged:
function rotateCounterClockwise(array){
for (let i = 0; i < array.length; i++){
console.log(array);
};
};
Step 4. Within the body of the for-loop, use array.shift() to remove the first element of the array, and assign it to a variable:
function rotateCounterClockwise(array){
for (let i = 0; i < array.length; i++){
console.log(array);
let firstElement = array.shift()
};
};
Step 5. Within the body of the for-loop, use array.push() to push the element stored in the firstElement variable to the end of the array:
function rotateCounterClockwise(array){
for (let i = 0; i < array.length; i++){
console.log(array);
let firstElement = array.shift();
array.push(firstLetter);
};
};
Step 6. Finally, call the function with the array of your choice as its argument:
function rotateCounterClockwise(array){
for (let i = 0; i < array.length; i++){
console.log(array);
let firstElement = array.shift();
array.push(firstLetter);
};
};
rotateCounterClockwise(arrayOfYourChoice);
Top comments (0)