- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reversing array without changing the position of certain elements JavaScript
We are required to write a JavaScript function that takes in an array of literals. The function should reverse the array without changing the index of '#' presents in an array, like below example −
Array [18,-4,'#',0,8,'#',5] should return −
[5, 8, "#", 0, -4, "#", 18]
Here, numbers should be reversed, excluding '#' while keeping the same index.
Example
const arr = [18, -4, '#', 0, 8, '#', 5]; const arr1 = [18, -4, 0, '#', 8, '#', 5]; const specialReverse = (arr = []) => { let removed = arr.reduce((acc, val, ind) => { return val === '#' ? acc.concat(ind) : acc; }, []); let reversed = arr.filter(val => val !== '#').reverse(); removed.forEach(el => reversed.splice(el, 0, '#')); return reversed; }; console.log(specialReverse(arr)); console.log(specialReverse(arr1));
Output
And the output in the console will be −
[ 5, 8, '#', 0, -4, '#', 18 ] [ 5, 8, 0, '#', -4, '#', 18 ]
- Related Articles
- Shift certain array elements to front of array - JavaScript
- Shifting certain elements to the end of array JavaScript
- Arrangement of words without changing the relative position of vowel and consonants?
- Reversing a string while maintaining the position of spaces in JavaScript
- How to change an object Key without changing the original array in JavaScript?
- Partially reversing an array - JavaScript
- Count unique elements in array without sorting JavaScript
- How to remove certain number elements from an array in JavaScript
- Changing the Position of List Markers using CSS
- Changing the Position of List Markers in CSS
- How to redirect website after certain amount of time without JavaScript?
- Finding the index position of an array inside an array JavaScript
- Changing an array in place using splice() JavaScript
- How to set the bottom position of 3D elements with JavaScript?
- Reversing the prime length words - JavaScript

Advertisements