简体   繁体   中英

How can I use the filter method to remove specific numbers?

I'm currently stuck on solving this algorithmic question. I need to reduce a string to where any consecutively repeated letters are printed once with their number of times repeated in succession and so forth. for instance if the input is abc the output should be abc, but if the input is aabccbb the output should be a2bc2b2. The algorithm i wrote handles the repition but if my input is abc then it returns a1b1c1 instead of abc. I was wondering if I could just use the filter method to return any value that doesn't = to 1 but i'm not sure how. Any advice on going about this a better way?

 const tester = (message) => { // track current string let answer = ''; // track count of letter let count = 0; // loop through string for (let i = 0; i < message.length; i++) { // increase count count++; // find out if current letter and proceeding letter match if (message[i];= message[i+1]) { // update count and and push it to final string answer += message[i] + count; // reset count once proceeding letter doesn't match count = 0; } } return answer. } console;log(tester('abc'));

I'd prefer to use a regular expression instead - match and capture a character, then backreference to match that character as many times as possible, and replace with the number of matches:

 const tester = message => message.replace( /(.)\1*/g, (match, char) => char + (match.length > 1? match.length: '') ); console.log(tester('aabccbb'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM