Swap kth element of array - JavaScript

We are required to write a JavaScript function that accepts an array of Numbers and a number, say k (k must be less than or equal to the length of array).

And our function should replace the kth element from the beginning with the kth element from the end of the array.

Understanding the Problem

When we say "kth element from beginning" and "kth element from end", we need to understand the positioning:

  • kth element from beginning: index = k - 1
  • kth element from end: index = array.length - k

Example

Following is the code −

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const swapKth = (arr, k) => {
    const { length: l } = arr;
    let temp;
    const ind = k-1;
    temp = arr[ind];
    arr[ind] = arr[l-k];
    arr[l-k] = temp;
};

swapKth(arr, 4);
console.log(arr);

swapKth(arr, 8);
console.log(arr);

Output

Following is the output in the console −

[
  0, 1, 2, 6, 4,
  5, 3, 7, 8, 9
]
[
  0, 1, 7, 6, 4,
  5, 3, 2, 8, 9
]

How It Works

Let's trace through the first swap (k=4) with array [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:

  • 4th element from beginning: index 3, value = 3
  • 4th element from end: index 6, value = 6
  • After swap: [0, 1, 2, 6, 4, 5, 3, 7, 8, 9]

Alternative Implementation

Here's a cleaner version using array destructuring:

const arr2 = [10, 20, 30, 40, 50];

const swapKthDestructured = (arr, k) => {
    const fromStart = k - 1;
    const fromEnd = arr.length - k;
    
    [arr[fromStart], arr[fromEnd]] = [arr[fromEnd], arr[fromStart]];
};

console.log("Before swap:", arr2);
swapKthDestructured(arr2, 2);
console.log("After swapping 2nd elements:", arr2);
Before swap: [ 10, 20, 30, 40, 50 ]
After swapping 2nd elements: [ 10, 40, 30, 20, 50 ]

Key Points

  • The function modifies the original array (in-place swap)
  • Use k-1 for the starting index and length-k for the ending index
  • Array destructuring provides a more elegant swapping syntax
  • Ensure k is within valid bounds (1 ? k ? array.length)

Conclusion

Swapping kth elements from start and end requires careful index calculation. The destructuring approach offers cleaner syntax while maintaining the same functionality.

Updated on: 2026-03-15T23:18:59+05:30

670 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements