JavaScript Program to Swap First and Last Elements in an Array
Last Updated :
12 Jul, 2024
In this article, we are going to learn about swaping the first and last elements in an array in JavaScript. Swaping the first and last elements in a JavaScript array refers to swapping their positions, effectively exchanging the values at these two distinct indices within the array.
There are several methods that can be used to interchange the first and last elements in an array in JavaScript, which are listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
Using Temporary Variable
Interchanging first and last array elements in JavaScript involves storing the first element in a temporary variable, and then swapping values between the first and last elements.
Syntax:
let temp = arr1[0];
arr1[0] = arr1[arr1.length - 1];
arr1[arr1.length - 1] = temp;
Example: In this example, we are using a temp variable to interchange 1st index value with the last index value of our array.
JavaScript
let arr1 = [10, 20, 30, 40, 50];
let temp = arr1[0];
arr1[0] = arr1[arr1.length - 1];
arr1[arr1.length - 1] = temp;
console.log("Array after interchange:", arr1);
OutputArray after interchange: [ 50, 20, 30, 40, 10 ]
Array Destructuring
In this approach we are using Array destructuring assigns values from an array to variables, swapping the first and last elements.
Syntax:
[array[0], array[array.length - 1]] = [array[array.length - 1], array[0]];
Example:
JavaScript
let array = [10, 2, 5, 12, 7];
[array[0], array[array.length - 1]] = [array[array.length - 1], array[0]];
console.log("Array after swapping : " + array);
OutputArray after swapping : 7,2,5,12,10
Using XOR Bitwise Operator
In this approach, the XOR (^) bitwise operator to interchange the values of the first and last elements in the array without using a temporary variable.
Syntax:
array[0] = array[0] ^ array[array.length - 1];
array[array.length - 1] = array[0] ^ array[array.length - 1];
array[0] = array[0] ^ array[array.length - 1];
Example: In this example we are using XOR operator to interchange the element in your given array.
JavaScript
const array = [1, 2, 3, 4, 5];
array[0] = array[0] ^ array[array.length - 1];
array[array.length - 1] = array[0] ^ array[array.length - 1];
array[0] = array[0] ^ array[array.length - 1];
console.log("Array after interchange:", array);
OutputArray after interchange: [ 5, 2, 3, 4, 1 ]
Using splice() Method
In this approach, splice() method is used to replace the last element with the first element, and the result is assigned back to the first position in the array. This effectively interchanges the values 12 and 55 in the array.
Syntax:
Array.splice( index, remove_count, item_list )
Example: In this example we are using the above-explained approach.
JavaScript
let myArray = [12, 22, 33, 44, 55];
myArray[0] = myArray.splice(myArray.length - 1, 1, myArray[0])[0];
console.log(myArray);
Output[ 55, 22, 33, 44, 12 ]
Using a for Loop
Using a for loop, the function swaps the first and last elements of an array by iterating through the array. When the loop index is zero, it temporarily stores the first element, assigns the last element to the first position, and places the stored element at the last position.
Example:
JavaScript
function swapFirstLast(arr) {
if (arr.length > 1) {
for (let i = 0; i < arr.length; i++) {
if (i === 0) {
let temp = arr[i];
arr[i] = arr[arr.length - 1];
arr[arr.length - 1] = temp;
break;
}
}
}
return arr;
}
console.log(swapFirstLast([1, 2, 3, 4, 5])); // [5, 2, 3, 4, 1]
console.log(swapFirstLast([10, 20, 30])); // [30, 20, 10]
console.log(swapFirstLast([7])); // [7]
Output[ 5, 2, 3, 4, 1 ]
[ 30, 20, 10 ]
[ 7 ]
Using push() and shift() Methods
In this approach, we use the push() method to add elements to the end of the array and the shift() method to remove the first element. We can use these methods to swap the first and last elements of the array.
Example: In this example, we are using push() and shift() methods to interchange the first and last elements of the array.
JavaScript
let array = [1, 2, 3, 4, 5];
let firstElement = array.shift();
let lastElement = array.pop();
array.unshift(lastElement);
array.push(firstElement);
console.log("Array after interchange:", array);
OutputArray after interchange: [ 5, 2, 3, 4, 1 ]
Similar Reads
JavaScript Program to Swap Two Elements in a Linked List
We are given a linked list and the task is to swap two elements in a linked list without disturbing their links. There are multiple ways to swap. It can be done by swapping the elements inside the nodes, and by swapping the complete nodes. Example: Input: list = 10 -> 11 -> 12 -> 13 -> 1
5 min read
Javascript Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1The approach is very
2 min read
JavaScript Program for Left Rotate by One in an Array
In this article, we are going to learn about left Rotation by One in an Array by using JavaScript, Left rotation by one in an array means shifting all elements from one position to the left, with the last element moving to the first position. The order of elements is cyclically rotated while maintai
5 min read
JavaScript Program to Interchange Elements of First & Last in a Matrix Across Columns
We are given a matrix and we have to interchange the elements of the first and last columns with each other in a matrix. Example: Input 1 : 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2Output 1 : 0 1 5 1 2 3 7 2 3 9 1 8 2 7 8 6Table of Content Using the swapping logicUsing forEach methodUsing the swapping logicIn
3 min read
JavaScript Program to Swap Characters in a String
In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsin
6 min read
JavaScript Program for Insertion Sort
What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program to Rearrange Array Alternately
Rearranging an array alternately means, If we have a sorted array then we have to rearrange the array such that the first largest element should come at index-0(0-based indexing), first smallest element should come at index-1, similarly, second largest element should come at index-3 and second small
7 min read
JavaScript Program to Find Minimum Number of Swaps to Sort Array
The minimum number of swaps to sort an array is the smallest quantity of element swaps needed to arrange the array in ascending or descending order. This minimizes the number of exchanges and is a key metric in sorting algorithms, as reducing swaps often improves efficiency and performance when orga
7 min read
JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd
In this article, we will cover rearranging arrays such that even positions are greater than odd in JavaScript. Give there is an array that we need to rearrange in the pattern where the even positioned are greater than the odd positioned in JavaScript. We will see the code for each approach along wit
4 min read
JavaScript Program for Quick Sort
What is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read