Q:

Callback Sort Function to sort an array by number of vowels

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
}

A:

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

