
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ]
- Related Articles
- Swap certain element from end and start of array - JavaScript
- Kth Largest Element in an Array
- Comparing adjacent element and swap - JavaScript?
- Kth Largest Element in an Array in Python
- How to swap two array elements in JavaScript?
- Python – Find Kth Even Element
- How to swap the key and value of JSON element using JavaScript?
- Find maximum sum taking every Kth element in the array in C++
- How to move an element of an array to a specific position (swap)?
- JavaScript Program for Block swap algorithm for array rotation
- C++ Program to find kth Smallest Element by the Method of Partitioning the Array\n
- Python – Extract Kth element of every Nth tuple in List
- JavaScript - array undefined element count
- Kth Smallest Element in a BST in Python
- Kth Largest Element in a Stream in Python

Advertisements