Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Repeat character depending on position in array + 1

I’m trying to get an output like this:

['h', 'ee', 'lll', 'llll', 'ooooo']

currently my out put is:

[ 'h', 'ee', 'lll', 'lll', 'ooooo' ]

The issue is the second occurrence of the "l" isn’t being repeated one more time because I’m counting the index of the letter then adding 1 and it is only counting the first occurrence of the "l".
This is the code I have so far, any help would be great.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function mumble(string) {
  string.toLowerCase();
  let arrayPush = [];
  let array = string.split("");
  let count = 0;
  let char = [];
  array.map((letter) => {
    count = array.indexOf(letter);

    arrayPush.push(letter.repeat(count + 1));
  });

  return arrayPush;
}

console.log(mumble("hello")); 

>Solution :

Don’t use indexOf, use the second parameter in the .map callback to determine the index (and from that, the number of times to repeat the string).

function mumble(string) {
  string.toLowerCase();
  let arrayPush = [];
  let array = string.split("");
  let count = 0;
  let char = [];
  array.map((letter, i) => {
    arrayPush.push(letter.repeat(i + 1));
  });

  return arrayPush;
}

console.log(mumble("hello")); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading