clusterBuddy
clusterBuddy

Reputation: 1554

javascript loop isn't re-iterating on 2nd counter

I have just fiddled around with javascript, I'm just trying to compare 2 arrays and remove all the english vowels from the string to later return it with no vowels.

The iteration for j representing the array of vowels (arr) stops at length but I want it to re-loop on every iteration for i.

Here is my basic code:

let sentence = 'eitan was here';

function disemvowel(str) {
  let arr = ['a', 'e', 'i', 'o', 'u'];
  let letters = str.split('');
  let i, j;
  for (i = 0, j = 0; i < letters.length && j < arr.length;) {
    console.log('counter: i = ' + i + ', j = ' + j + ', ' + letters[i] + ' vs ' + arr[j] + 'and letters: ' + letters);
    if (letters[i] == arr[j]) {
      if (letters[i] == ' ') {
        i++;
      }
      console.log('IF stopped here: ' + letters[i] + ' at i: ' + i + ', ' + arr[j] + ' at j: ' + j);
      letters.splice(i, 1);
      //console.log('letters after splice: '+ letters);
      i++;
    } else {
      console.log('ELSE stopped here: ' + letters[i] + ' at i: ' + i + ', ' + arr[j] + ' at j: ' + j);
      j++;
    }
  }
  return letters;

}
console.log('letters are: ', disemvowel(sentence));
I'm interested to avoid creating loops within loops or separate functions to run j for runtime and brevity.

Upvotes: 1

Views: 59

Answers (3)

Mahesh Hegde
Mahesh Hegde

Reputation: 184

You have to reset j to 0. Also, You can not splice the same array that you are looping through i.e letters array in this case.

<script>
 let sentence = 'eitan was here';
 function disemvowel(str) {
  let arr = ['a', 'e', 'i', 'o', 'u'];
  let letters = str.split('');
  let output = [];
  let i,j;
 for (i=0,j=0; i<letters.length && j<arr.length;){
    if(letters[i] == arr[j]){
        j = 0;
        i++;
    }else{
        j++;
        if(j >= arr.length){
            output.push(letters[i]);
            i++;
            j = 0;
        }
     }
   }
  return output;
 }
 console.log('letters are: ', disemvowel(sentence));
</script>

Upvotes: 0

dam2299
dam2299

Reputation: 34

sentence = 'eitan was here';
function disemvowel(str){
arr = ['a','e','i','o','u'];

arr.forEach((itm)=>{
    var re = new RegExp(itm,'g');
    str = str.replace(re,'');
})
return str;
}
console.log(disemvowel(sentence));

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You do not need to loop over to remove the vowels from the string. The best way to achieve this is to use character class in replace() like this

let sentence = 'eitan was here';
sentence  = sentence .replace(/[aeiou]/g,'');

You can also use the OR operator (|) like this

sentence = sentence.replace(/a|e|i|o|u/g,''); 

Upvotes: 3

Related Questions