0

I am trying to apply a break in my forEach loop. I don't think it is possible to actually use a break in a forEach (not 100% why, I have just read about it and am trusting it).

Here is my code:

function translate(wordString){

var vowel = 'aeiou';
var wordArr = wordString.split(' ');
var wordArray = [];
wordArr.forEach(function(word){


    if(vowel.search(word.charAt(0))!=-1){
        wordArray.push(word + 'ay');
        //WOULD LIKE TO PUT BREAK HERE;
        // break;

    }
    else{
        index = 0;
    }
    for(var i =0; i< word.length; i++){
        if(vowel.search(word.charAt(i)) !=-1){
            if(word.charAt(i) != 'u' || (word.charAt(i) == 'u' && word.charAt(i - 1) != 'q')){
                index = i;
                break;
            }
        }
    }
    wordArray.push(word.substring(index, word.length) + word.substring(0, index) + 'ay');
  });
  return wordArray.join(' ');
}

translate('apple');

When I pass a word that starts with a vowel, I get a duplicated word, I would like to just have the loop break whenever it steps inside my first if statement. Is this possible?

These are the last two tests I need to pass, I think they will be solved if I can somehow stop the loop at the indicated spot.

Here is a repl.it link http://repl.it/Nv6

http://repl.it/Nv6

HelloWorld
  • 10,529
  • 10
  • 31
  • 50

2 Answers2

3

Use .some() instead of .forEach(), and return true when you want to break.

Or .every(), and return false to break.

cookie monster
  • 10,671
  • 4
  • 31
  • 45
0
    //...
    //WOULD LIKE TO PUT BREAK HERE;
    // break;
    return;

'return' works for me.

Eric
  • 2,115
  • 2
  • 20
  • 29
  • Just FYI, that will halt the callback in the current iteration of the `.forEach()`, but it won't halt the iterations like a `break` would on a `for` loop. – cookie monster Jan 17 '14 at 19:00
  • If you wanted to end all the iterations, you could throw a typed exception and ignore it. Something like `function Foo(){}` and `throw new Foo();` and try { } catch(e if e instanceof Foo) {}` – Eric Jan 17 '14 at 22:37