 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements
 