We are required to write a JavaScript function that accepts an array of Numbers and a number, say n (n must be less than or equal to the length of array). And our function should replace the kth element from the beginning with the nth 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 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; }; swapKth(arr, 4); console.log(arr); swapNth(arr, 8); console.log(arr);
Output
This will produce the following output in console −
[ 0, 1, 2, 6, 4, 5, 3, 7, 8, 9 ] [ 0, 1, 7, 6, 4, 5, 3, 2, 8, 9 ]