1

I'm writing a program that removes vowels from str parameter and I've decided to use a switch statement to achieve this goal. I'm pretty bad at explaining stuff so I'll give you an example:

No offense but,\nYour writing is among the worst I've ever read

Should become

N ffns bt,\nYr wrtng s mng th wrst 'v vr rd

But my output looks like this:

N ffns bt,\nYur wrtng s mng th wrst 'v vr rad

The program decided to leave "u" and "a" for some reason. After nearly 1,5h of looking for a cause, I give up because I have literally no clue what I did wrong.

function disemvowel(str) {
  let arr = str.split(''); // str -> arr
  for (let x = 0; x <= arr.length; x++) { // remove vowels
    switch(arr[x]) {
      case "a":
      case "e":
      case "i":
      case "o":
      case "u":
      case "A":
      case "E":
      case "I":
      case "O":
      case "U":
        arr.splice(x, 1);
        break;  
    }
  }
  str = arr.join([separator = '']) // arr -> str
  return str;
}
Andy
  • 61,948
  • 13
  • 68
  • 95
waysenpai
  • 31
  • 3
  • 4
    Try running your loop backwards, this is a classic error when traversing a result that mutates. – Keith Nov 22 '21 at 14:00
  • 1
    As a side note, JavaScript doesn't have named arguments. `[separator = '']` will evaluate to `''` (due to the argument being converted to a string). Just use `arr.join('')` directly. – Ivar Nov 22 '21 at 14:14

1 Answers1

3

The array length is changing after every splice. You can define the length at first and decrement x every time you delete an item:

function disemvowel(str) {
  let arr = str.split(''); // str -> arr
  const length = arr.length;
  for (let x = 0; x < length; x++) { // remove vowels
    switch(arr[x]) {
      case "a":
      case "e":
      case "i":
      case "o":
      case "u":
      case "A":
      case "E":
      case "I":
      case "O":
      case "U":
        arr.splice(x, 1);
        x--;
        break;  
    }
  }
  str = arr.join([separator = '']) // arr -> str
  return str;
}

console.log(
  disemvowel("No offense but,\nYour writing is among the worst I've ever read")
);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48