w3resource

JavaScript: Swap the first and last elements of a given array of integers

JavaScript Basic: Exercise-80 with Solution

Swap First and Last Elements in Array

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:

JavaScript: Swap the first and last elements of a given array of integers.

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:

Flowchart: JavaScript - Swap the first and last elements of a given array of integers

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]));

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that swaps the first and last elements of an array and returns the updated array.
  • Write a JavaScript function that performs an in-place swap of an array’s first and last elements, handling arrays with a single element correctly.
  • Write a JavaScript program that checks if an array has at least one element before swapping its first and last items without using a temporary variable.

Go to:


PREV : Check if Array Contains 30 and 40 Twice.
NEXT : Add Two Digits in a Two-Digit Number.

Improve this sample solution and post your code through Disqus.

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.