Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
JS switch statement works only sometimes

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;
}

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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")
);

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!