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

I am trying to filter an array against another array using Every () because Every () loops through the array and stops as soon as it returns false. However, I am trying to get it to return a new array from another array and stop it after being false.

For example, I have this word "chance" and this array of vowels = ["a", "e", "i", "o", "u"] . So I wanted to match each letter in "random" with this vowel array and extract "ch" and stop if "a" in "random" matches the vowel 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 get it to work to get the "ch" in the new array.

+3


source to share


2 answers


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



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

Run code


+1


source


You cannot do this. The function is every()

meant to return boolean

for each tested item.
But in it, you can add letters to the array newletters

and then return true

.
And in case of vowel match, just return false

to end the function every()

. Thus, at the end of the processing newletters

is assessed as needed.



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

    }
  }

      

0


source







All Articles