Removing n characters from a string in alphabetical order in JavaScript



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
Updated on: 2021-04-20T07:26:45+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements