Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Swap certain element from end and start of array - JavaScript
We need to write a JavaScript function that accepts an array of numbers and a position k, then swaps the kth element from the beginning with the kth element from the end of the array.
Understanding the Problem
For an array with indices 0 to n-1, the kth element from start is at index k-1, and the kth element from end is at index n-k. We swap these two elements.
Example Implementation
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const swapNth = (arr, k) => {
const { length: l } = arr;
let temp;
const ind = k - 1;
temp = arr[ind];
arr[ind] = arr[l - k];
arr[l - k] = temp;
};
console.log("Original array:", arr);
swapNth(arr, 4);
console.log("After swapping 4th elements:", arr);
swapNth(arr, 8);
console.log("After swapping 8th elements:", arr);
Original array: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] After swapping 4th elements: [ 0, 1, 2, 6, 4, 5, 3, 7, 8, 9 ] After swapping 8th elements: [ 0, 1, 7, 6, 4, 5, 3, 2, 8, 9 ]
How It Works
The function calculates two indices:
- Start index: k-1 (4th element is at index 3)
- End index: length-k (4th from end in 10-element array is at index 6)
It then uses a temporary variable to swap the values at these positions.
Alternative Using Destructuring
const swapNthDestructuring = (arr, k) => {
const startIndex = k - 1;
const endIndex = arr.length - k;
[arr[startIndex], arr[endIndex]] = [arr[endIndex], arr[startIndex]];
};
const testArray = [10, 20, 30, 40, 50, 60];
console.log("Before swap:", testArray);
swapNthDestructuring(testArray, 2);
console.log("After swapping 2nd elements:", testArray);
Before swap: [ 10, 20, 30, 40, 50, 60 ] After swapping 2nd elements: [ 10, 50, 30, 40, 20, 60 ]
Conclusion
This swap operation is useful for array manipulation tasks. The destructuring approach provides cleaner syntax while the traditional method offers better clarity for the swapping logic.
Advertisements
