JavaScript: Rotate the elements left of a given array of integers of length 3
JavaScript Basic: Exercise-70 with Solution
Write a JavaScript program to rotate the elements left in a given array of integers of length 3.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named rotate_elements_left with a parameter array
function rotate_elements_left(array)
{
// Return a new array with elements rotated to the left
// The new order is [array[1], array[2], array[0]]
return [array[1], array[2], array[0]];
}
// Call the function with sample arguments and log the results to the console
console.log(rotate_elements_left([3, 4, 5]));
console.log(rotate_elements_left([0, -1, 2]));
console.log(rotate_elements_left([7, 6, 5]));
Output:
[4,5,3] [-1,2,0] [6,5,7]
Live Demo:
See the Pen JavaScript - Rotate the elements left of a given array of integers of length 3 - basic-ex-70 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Define a function named rotate_elements_left with a parameter array using arrow function syntax
const rotate_elements_left = array => {
// Use array destructuring to rearrange elements
const [second, third, first] = array;
// Return a new array with elements rearranged
return [second, third, first];
};
// Call the function with sample arguments and log the results to the console
console.log(rotate_elements_left([3, 4, 5]));
console.log(rotate_elements_left([0, -1, 2]));
console.log(rotate_elements_left([7, 6, 5]));
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to compute the sum of three elements of a given array of integers of length 3.
Next: JavaScript program to check if 1 appears in first or last position of a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics