Computer >> Computer tutorials >  >> Programming >> Javascript

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.

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
]