JavaScript: Reverse the elements of a given array of integers length 3
JavaScript Basic: Exercise-73 with Solution
Write a JavaScript program to reverse the elements of a given array of integers of length 3.
The program reverses the order of elements in an array of integers of length 3. It swaps the first and last elements, resulting in the array being in reverse order from its original state.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named reverse3 that takes an array as a parameter
function reverse3(array) {
// Use the map method to iterate over the array and reverse the order
return array.map((element, idx, arr) => arr[(arr.length - 1) - idx]);
}
// Call the function with sample arguments and log the results to the console
console.log(reverse3([5, 4, 3])); // Output: [3, 4, 5]
console.log(reverse3([1, 0, -1])); // Output: [-1, 0, 1]
console.log(reverse3([2, 3, 1])); // Output: [1, 3, 2]
Output:
[3,4,5] [-1,0,1] [1,3,2]
Live Demo:
See the Pen JavaScript - Reverse the elements of a given array of integers length 3 - basic-ex-73 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Define a function named reverse3 that takes an array as a parameter
const reverse3 = (array) => array.map((element, idx, arr) => arr[(arr.length - 1) - idx]);
// Call the function with sample arguments and log the results to the console
console.log(reverse3([5, 4, 3])); // Output: [3, 4, 5]
console.log(reverse3([1, 0, -1])); // Output: [-1, 0, 1]
console.log(reverse3([2, 3, 1])); // Output: [1, 3, 2]
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to check if the first and last elements are equal of a given array of integers length 3.
Next: JavaScript program to find the larger value between the first or last and set all the other elements with that value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-73.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics