w3resource

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.

Pictorial Presentation:

JavaScript: Reverse the elements of a given array of integers length 3.

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] 

Sample 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:

Flowchart: JavaScript - Reverse the elements of a given array of integers length 3

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]

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.



Follow us on Facebook and Twitter for latest update.