Computer >> Computer tutorials >  >> Programming >> Javascript

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
]