Skip to content

Reverse an array in JavaScript without changing the index of special character

const reverseArr = (arr, char) => {
   let start = 0, end = arr.length - 1, tmp;
   while(start < end){
      if(arr[start] === char){
         start++;
         continue;
      };
      if(arr[end] === char){
         end--;
         continue;
      };
      tmp = arr[start];
      arr[start] = arr[end];
      arr[end] = tmp;
      start++;
      end--;
   };
};
let arr = [1,2,3,'.',5,'.',5];
reverseArr(arr, '.');
console.log(arr); //[ 5,5,3,'.',2,'.',1 ]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.