函数显示单词中出现的最大字母

Function to show max occurring letter in word?

本文关键字:显示 单词中 函数      更新时间:2023-09-26

我正在尝试编写一个函数,该函数将识别具有最多重复字母的单词,并且我将其分解到目前为止以识别句子中出现的大多数字母,但我不确定现在如何将返回改为每个单词中重复字母的总数,而不是每个句子中重复字母的总数。

function letRepeat(str) {
    var letArray = {};
    for (var i = 0; i < str.length; i++) {
        letArray[str[i]] = (letArray[str[i]] || 0) + 1;
    }
    var max = 0;
    for (i in letArray) {
        max = Math.max(max, letArray[i]);
    }
    return letArray;
}
console.log(letRepeat("Hello there Larry Gormoon!"));
输出:

[object Object] {
   : 3,
  !: 1,
  a: 1,
  e: 3,
  G: 1,
  H: 1,
  h: 1,
  l: 2,
  L: 1,
  m: 1,
  n: 1,
  o: 4,
  r: 4,
  t: 1,
  y: 1
}

还有,知道为什么[object Object]引导输出吗?

我将把它分成两个独立的函数。

对一个单词中的字符进行计数,返回一个包含该单词的数组,以及最大重复数。

function repCount (word) {
  var orig = word,
      len = word.length,
      mem = {},
      max = 0,
      char, i;
  word = word.toLowerCase();
  for (i = 0; i < len; i++) {
    char = word[i];
    mem[char] = mem[char] + 1 || 1;
    if (mem[char] > max) {
      max = mem[char];
    } 
  }
  return [orig, max];
}

另一个使用第一个,检查句子中的每个单词。你会想要在脑海中决定一个单词是由什么组成的。对我来说,它是由字母、撇号和连字符组成的完整序列。其他人可能会在空白字符上分裂。两者各有缺点。

function mostRepLet (str) {
  var words = str.match(/['w'-]+/gi),
      len = words.length,
      most = ['', 0],
      chk, i;
  for (i = 0; i < len; i++) {
    chk = repCount(words[i]);
    if (chk[1] > most[1]) {
      most = chk;
    }
  }

  return most[0];
}

var phrase = 'Hello there Larry Gormoon!';
function repCount (word) {
  var len = word.length,
      mem = {},
      max = 0,
      char, i;
  
  
  for (i = 0; i < len; i++) {
    char = word[i];
    
    mem[char] = mem[char] + 1 || 1;
    
    if (mem[char] > max) {
      max = mem[char];
    } 
  }
  
  return [word, max];
}
function mostRepLet (str) {
  var words = str.match(/['w'-]+/gi),
      len = words.length,
      most = ['', 0],
      chk, i;
  
  for (i = 0; i < len; i++) {
    chk = repCount(words[i]);
    
    if (chk[1] > most[1]) {
      most = chk;
    }
  }
  
  
  return most[0];
}
alert(mostRepLet(phrase));


return letArray表示[object Object],因为这正是letArray。JavaScript中没有关联数组。有对象,基本上只是属性值对,还有Array对象,这是一种特殊的对象,具有数字索引的属性,还有length属性。

花括号创建一个对象字面值:{}

括号创建Array字面值:[]

在ES6中,有Map对象

如果你想要每个单词重复的字母总数,你只需要把句子分成单词,然后稍微修改一下你的代码。

function countWordRpt(str) {
  var countObj = {};
  // Split the string into words,
  // and count the repeated letters in each word. 
  str.split(' ').forEach(function(word) {
    countObj[word] = function countLetRpt() {
      var letCount = {};
      // Count the repeated letters in each word.
      word.split('').forEach(function(letter) {
        letCount[letter] = ++letCount[letter] || 1;
      });
      // Find out the most repeated letters. 
      // There may be several letters repeated for most times,
      // so I use an array here.
      var max = [];
      for (var i in letCount) {
        if (letCount.hasOwnProperty(i)) {
          if (letCount[max[0]] < letCount[i] || max.length === 0) {
            max = [i];
          } else if (letCount[max[0]] === letCount[i]) {
            max.push(i);
          }
        }
      }
      letCount.max = {
        letters: max,
        count: letCount[max[0]]
      };
      return letCount;
    }();
  });
  // Find out the most repeated words in the sentence.
  // Almost the same logic as above. 
  // Also, the words can be more than one, so use an array.
  var max = [];
  for (word in countObj) {
    if (countObj.hasOwnProperty(word)) {
      if (max.length === 0 ||
        countObj[word].max.count > countObj[max[0]].max.count) {
        max = [word];
      } else if (countObj[word].max.count === countObj[max[0]].max.count) {
        max.push(word);
      }
    }
  }
  countObj.max = {
    words: max,
    count: countObj[max[0]].max.count
  };
  return countObj;
}
var str = 'Hello there Larry Gormoon!';
console.log(countWordRpt(str));

输出:

{
    "Hello": {
        "H": 1, 
        "e": 1, 
        "l": 2, 
        "o": 1, 
        "max": {
            "letters": [
                "l"
            ], 
            "count": 2
        }
    }, 
    "there": {
        "t": 1, 
        "h": 1, 
        "e": 2, 
        "r": 1, 
        "max": {
            "letters": [
                "e"
            ], 
            "count": 2
        }
    }, 
    "Larry": {
        "L": 1, 
        "a": 1, 
        "r": 2, 
        "y": 1, 
        "max": {
            "letters": [
                "r"
            ], 
            "count": 2
        }
    }, 
    "Gormoon!": {
        "G": 1, 
        "o": 3, 
        "r": 1, 
        "m": 1, 
        "n": 1, 
        "!": 1, 
        "max": {
            "letters": [
                "o"
            ], 
            "count": 3
        }
    }, 
    "max": {
        "words": [
            "Gormoon!"
        ], 
        "count": 3
    }
}

这段代码将返回一个对象,其中单词作为键,其值作为对象,其中包含每个字母的出现次数。它还生成一个键/值对,指示在所有单词中哪个单词出现次数最多。注意,在这段代码中,如果有两个单词具有相同的高出现次数,它将选择最后一个要处理的单词作为总数。

function letRepeat(str) {
    var totals = {};
    // split the words into an array
    // use reduce but pass in an inital object so our output
    // is also an object
    return str.split(' ').reduce(function (p, c) {
        totals[c] = 0;
        // split each word down into letters
        // if the letter is not in the "letters object" add it
        // increment the value count
        p[c] = c.split('').reduce(function (p2, c2) {
            p2[c2] = ++p2[c2] || 1;
            if (p2[c2] > 1) totals[c]++;
            return p2;
        }, {});
        // find the word with the highest letter reoccurence
        var highest = Object.keys(totals).reduce(function (a, b) {
            return totals[a] > totals[b] ? a : b;
        });
        p.highest = { word: highest, reoccurences: totals[highest] };
        return p;
    }, {});
}
letRepeat("Hello there Larry Gormoon!");

演示输出:

Gormoon在这里是最高的,因为"o"重复出现了2次以上。

{
  "Hello": {
    "H": 1,
    "e": 1,
    "l": 2,
    "o": 1
  },
  "highest": {
    "word": "Gormoon!",
    "reoccurences": 2
  },
  "there": {
    "t": 1,
    "h": 1,
    "e": 2,
    "r": 1
  },
  "Larry": {
    "L": 1,
    "a": 1,
    "r": 2,
    "y": 1
  },
  "Gormoon!": {
    "G": 1,
    "o": 3,
    "r": 1,
    "m": 1,
    "n": 1,
    "!": 1
  }
}