Kristina Bressler
Kristina Bressler

Reputation: 1732

How to use Every() to return a new array in Javascript?

I'm trying to filter out an array against another array, using Every() because Every() loop through an array and stop once it return false. However, I'm trying to make it return the new array from other array and stop once it's false.

For example, I have this word "chance" and this array vowels = ["a", "e", "i", "o", "u"]. So I wanted to match every letter in "chance" to this vowels array and extract "ch" and stop if "a" in "chance" match the vowels array.

Here's my code

function extract(str) {

  var vowels = ["a", "e", "i", "o", "u"];
  var word = str.split("");
  var newletters = [];
  var firstletter = str[0];

  for (var i = 0; i <= vowels.length; i++) {
    if (firstletter !== vowels[i]) {
      word.every(function(letter){
        if (letter.indexOf(vowels[i]) === -1 ){
        return newletters.push(letter);
        } else {
        return false;
        }
      })

    }
  }

  //return str;
}

console.log(extract("chance"));

I couldn't figure out how to make it works to get "ch" in new array.

Upvotes: 3

Views: 77

Answers (2)

SLePort
SLePort

Reputation: 15461

You can join vowels and use the resulting string in a regex:

function extract(str) {
  var vowels = ["a", "e", "i", "o", "u"];
  var regex = new RegExp("(.*?)[" + vowels.join("") + "]");
  if (str.match(regex) != null && str != "") {
    console.log(str.match(regex)[1]);
    //newletters.push(str.match(regex)[1]);
  }
}

extract("chance");

Upvotes: 1

davidxxx
davidxxx

Reputation: 131346

You cannot do it.
every() function is designed to return a boolean for each tested element.
But in it, you could add letters in newletters array and then return true.
And in case of vowel matching, just return false to end the every() function. In this way, at the end of the processing, newletters is valued as required.

 for (var i = 0; i <= vowels.length; i++) {
    if (firstletter !== vowels[i]) {
      word.every(function(letter){
        if (letter.indexOf(vowels[i]) === -1 ){
            newletters.push(letter);
            return true;
         }             
         return false;            
      })

    }
  }

Upvotes: 0

Related Questions