

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 certain element from end and start of array - JavaScript
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 ]
- Related Questions & Answers
- Removing 0s from start and end - JavaScript
- Swap kth element of array - JavaScript
- Shifting certain elements to the end of array JavaScript
- Removing an element from the start of the array in javascript
- Removing an element from the end of the array in Javascript
- Comparing adjacent element and swap - JavaScript?
- Display all the numbers from a range of start and end value in JavaScript?
- How to extract values from an R data frame column that do not start and end with certain characters?
- Adding an element at the start of the array in Javascript
- Adding an element at the end of the array in Javascript
- Beginning and end pairs in array - JavaScript
- Shift certain array elements to front of array - JavaScript
- How to exclude certain values from randomly generated array JavaScript
- What are start angle and end angle of arc in HTML5 canvas?
- How to remove certain number elements from an array in JavaScript
Advertisements