1

I am trying to sort this array by its the number of its vowels using sort() callback function.

So far, i have my function to get the number of vowels but don't know how to implement it in sort() as a callback.

var array = [
    "abc",
    "december",
    "ax",
    "cv",
    "veeeeee",
    "colo",
    "bobola",
    "lax",
    "cri",
    "nahamua",
    "pip"
];

Here is my function to get number of vowels in a word.

function isVowel(x) {
  var result;
  result = x.toLowerCase() == "a" || x == "e" || x == "i" || x == "o" || x == "u";
  return result;
}

function countVowels(strChar) {
  var token = strChar.split('') // array of words
  var countVowel = token.filter(isVowel)
  return 'number of vowels: ' + countVowel.length
}
Huy Le
  • 491
  • 2
  • 6
  • 11
  • Don't return a string from your `countVowels` function but the integer, and then just [use it to compare the two words by their counts](https://stackoverflow.com/a/1063027/1048572) – Bergi Feb 24 '18 at 02:30

1 Answers1

1

This approach sorts by the count of vowels, so a word without vowels will be placed in first positions.

  • Look how the function isVowel uses a regex /[aeiou]/i.
  • Basically, the callback calback(a, b) for the function sort subtracts the count of vowels per word to get 0 equals, > 0 a is greater and < 0 b is greater.

var array = [
    "abc",
    "december",
    "ax",
    "cv",
    "veeeeee",
    "colo",
    "bobola",
    "lax",
    "cri",
    "nahamua",
    "pip",
    "zsw",
    "bcfw"
];

function isVowel(x) {
  //var result;
  //result = x.toLowerCase() == "a" || x == "e" || x == "i" || x == "o" || x == "u";
  //return result;

  return (/[aeiou]/i).test(x); 
}

function countVowels(strChar, strchar2) {
  var count1 = strChar.split('').filter(isVowel).length;
  var count2 = strchar2.split('').filter(isVowel).length;
  
  if (count1 === count2) return strChar.localeCompare(strchar2);
  
  return count1 - count2
}

array.sort(countVowels);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
  • is there a way to sort alphabetically for those that have the same number of vowels? – Huy Le Feb 24 '18 at 02:43
  • `isVowel` should return a boolean, not an array. Use `test` instead of `match`. Or just the OPs existing simple function. – Bergi Feb 24 '18 at 02:48
  • @Bergi yes, you're right. Is working because the function match returns null or !null. Answer updated! – Ele Feb 24 '18 at 02:51