【问题标题】:Callback Sort Function to sort an array by number of vowels回调排序函数按元音数对数组进行排序
【发布时间】:2018-02-24 02:23:19
【问题描述】:

我正在尝试使用 sort() 回调函数按元音的数量对该数组进行排序。

到目前为止,我有我的函数来获取元音的数量,但不知道如何在 sort() 中作为回调实现它。

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

这是我获取单词中元音数量的函数。

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
}

【问题讨论】:

标签: javascript node.js data-structures callback


【解决方案1】:

这种方法按元音的数量进行排序,因此没有元音的单词将被放在首位。

  • 看看函数 isVowel 如何使用正则表达式 /[aeiou]/i
  • 基本上,函数sort的回调calback(a, b)减去每个单词的元音计数得到0等于,> 0a更大,< 0 b 更大。

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

【讨论】:

  • 有没有办法按字母顺序对元音数量相同的人进行排序?
  • isVowel 应该返回一个布尔值,而不是一个数组。使用test 而不是match。或者只是 OP 现有的简单功能。
  • @Bergi 是的,你是对的。正在工作,因为函数 match 返回 null 或 !null。答案已更新!
猜你喜欢
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
相关资源
最近更新 更多