Evan Emolo
Evan Emolo

Reputation: 1670

JavaScript .forEach() and .splice() not working as expected

I am attempting to write a simple program to remove vowels and spaces from a string. There is some errant behavior to the following code that I cannot explain.

var vowels, testString, splitString, disemvoweled;

vowels = ['a', 'e', 'i', 'o', 'u'];
testString = 'the quick brown fox jumped over the lazy dog';
splitString = testString.split('');

splitString.forEach(function (char) {
    vowels.forEach(function (vowel) {
      if (char === vowel || char === ' ') {
        splitString.splice(splitString.indexOf(char), 1);
      }
    });
 });

disemvoweled = splitString.toString();
console.log(disemvoweled);  // 't,h,q,i,c,k,b,r,w,n,f,x,j,m,p,d,v,r,t,h,l,z,y,d'

In the returned string above, you will see an i in the 4th position. Additionally, the g for dog was not included in the result. Clearly, something is not working as expected. Can someone explain why this is happening?

Upvotes: 0

Views: 429

Answers (2)

David Aurelio
David Aurelio

Reputation: 504

your call to splice(index, 1) removes the array element at index, shifting all following indexes by one.

Since this is happening inside the forEach-loop, you make the outer loop skip the check of the character following that vowel.

You could use filter() instead to avoid mutating the array you are iterating:

splitString
  .filter(function(character) { return vowels.indexOf(character) === -1; })
  .toString();

Upvotes: 3

jfriend00
jfriend00

Reputation: 707218

I'm not sure why you don't just use .replace() to remove vowels and spaces:

var testString = 'the quick brown fox jumped over the lazy dog';
var newString = testString.replace(/[aeiou\s]/ig, "");

If you then want it a comma separated string, you can do that too:

newString = newString.split("").join(",");

Working demo: http://jsfiddle.net/jfriend00/x3sXW/

Upvotes: 3

Related Questions