我试图从数组中获得最流行/最常用的词,但我尝试了以下方法,但与其说“Rain”(雨),不如将其显示在控制台内,而不是[rain:2,hot:1]。

我究竟做错了什么?我只想显示第一个最受欢迎的单词而没有数字。

任何帮助/建议都将有所帮助,谢谢。

  var defaultArray = [{age:"25-35",country:"united kingdom",sex:"male",word:"rain"},{age:"25-35",country:"united arab emirates",sex:"male",word:"hot"},{age:"25-35",country:"zimbabwe",sex:"female",word:"rain"}];

  /* Popular */
  function popular() {
    var words = [];
    for(var p = 0; p < defaultArray.length; p++){
      var word = defaultArray[p].word;
      words.push(word);
      console.log(words);
    }
    var count = [];
    for (var i = 0, j = words.length; i < j; i++) {
      if (count[words[i]]) {
        count[words[i]]++;
      }
      else {
        count[words[i]] = 1;
      }
    }
    console.log(count);
  }
  popular();

最佳答案

与您原来的功能保持一致。您可以稍作调整即可获得最受欢迎的单词。注意:这不考虑联系。

var defaultArray = [
  {age:"25-35",country:"united arab emirates",sex:"male",word:"hot"},
  {age:"25-35",country:"united kingdom",sex:"male",word:"rain"},
  {age:"25-35",country:"united arabemirates",sex:"male",word:"hot"}];

/* Popular */
function popular() {
  var count = 0
  var max=0;
  var currentword="";
  var words = [];

  for(var p = 0; p < defaultArray.length; p++){
    var word = defaultArray[p].word;
    words.push(word);
  }

  for (var i = 0; i<words.length; i++) {
    if (max<=count){
      max=count;
    }
    count=0;
    for (var x=0; x<words.length; x++)
    {
      if (words[i]==words[x] ){
        count++;
      }
      if (count>max)currentword=words[i];
    }
  }
  console.log(currentword);
}

09-25 17:53