JavaScript: Swap the first and last elements of a given array of integers
JavaScript Basic: Exercise-80 with Solution
Write a JavaScript program to swap the first and last elements of a given array of integers. The array length should be at least 1.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Function to swap the first and last elements of an array
function swap(arra) {
// Destructuring assignment to swap values without using a temporary variable
[arra[0], arra[arra.length - 1]] = [arra[arra.length - 1], arra[0]];
// Return the modified array
return arra;
}
// Example usage
console.log(swap([1, 2, 3, 4]));
console.log(swap([0, 2, 1]));
console.log(swap([3]));
Output:
[4,2,3,1] [1,2,0] [3]
Live Demo:
See the Pen JavaScript - swap the first and last elements of a given array of integers - basic-ex-80 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// ES6 version using array destructuring and swapping
const swap = (arra) => {
[arra[0], arra[arra.length - 1]] = [arra[arra.length - 1], arra[0]];
return arra;
};
// Example usage
console.log(swap([1, 2, 3, 4]));
console.log(swap([0, 2, 1]));
console.log(swap([3]));
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to test if a given array of integers contains 30 and 40 twice.
Next: Write a JavaScript program to add two digits of a given positive integer of length two.
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://w3resource.com/javascript-exercises/javascript-basic-exercise-80.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics