Skip to content

Instantly share code, notes, and snippets.

@hendrixthecoder
Last active April 21, 2025 08:56
Show Gist options
  • Save hendrixthecoder/c9868bd2104fdbcf4feedc189bf795b4 to your computer and use it in GitHub Desktop.
Save hendrixthecoder/c9868bd2104fdbcf4feedc189bf795b4 to your computer and use it in GitHub Desktop.
Solution for problem "Given an array of words, group them by word length, then sort within each group based on the number of vowels in the word (descending), and finally, for ties, use alphabetical order (case-insensitive)"
const wordGroup = [
"apple", "orange", "pear", "grape",
"kiwi", "Avocado", "banana", "fig", "Apricot"
];
const getVowelCount = (str) => {
const vowels = ["a", "e", "i", "o", "u"];
let vowelCount = 0;
for(let i = 0; i < str.length; i++){
if(vowels.includes(str[i].toLowerCase())){
vowelCount++;
}
}
return vowelCount
};
const getSortedArrayByWordCount = (wordCount, arr) => {
const filteredArrayByWordCount = arr.filter((elem) => elem.length === wordCount);
const result = [];
filteredArrayByWordCount.forEach((elem) => {
if(!result.length) {
result.push(elem)
return;
}
for(let i = 0; i < result.length; i++){
const elemVowelCount = getVowelCount(elem);
const iVowelCount = getVowelCount(result[i]);
if(elemVowelCount > iVowelCount){
result.splice(i, 0, elem);
break;
}
if(elemVowelCount === iVowelCount) {
if(result[i].toLowerCase() > elem.toLowerCase()) {
result.splice(i, 0, elem)
break;
}
}
if(i === result.length - 1) {
result.push(elem)
break;
}
}
})
return result;
}
const sort = (arr) => {
return [...arr].reduce((acc, curr) => {
if(!acc[curr.length]){
acc[curr.length] = getSortedArrayByWordCount(curr.length, arr);
}
return acc;
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment