Removing n characters from a string in alphabetical order in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a lowercase alphabet string and number num.

Our function should remove num characters from the array in alphabetical order. It means we should first remove ‘a’ if they exist then ‘b’ , ‘c’ and so on until we hit the desired num.

Example

Following is the code −

 Live Demo

const str = 'abascus';
const num = 4;
const removeAlphabetically = (str = '', num = '') => {
   const legend = "abcdefghijklmnopqrstuvwxyz";
   for(let i = 0; i < legend.length; i+=1){
      while(str.includes(legend[i]) && num > 0){
         str = str.replace(legend[i], "");
         num -= 1;
      };
   };
   return str;
};
console.log(removeAlphabetically(str, num));

Output

Following is the console output −

sus
raja
Published on 20-Apr-2021 07:26:07
Advertisements