【问题标题】:Understanding function to find mode了解查找模式的功能
【发布时间】:2017-01-26 23:02:24
【问题描述】:

希望这是一个可以在这里问的问题... 所以我得到了一些帮助来创建一个函数来查找模式(在数组中出现次数最多的数字)。但现在我需要一点帮助来理解它...... (我是编程新手) 数据是保存“信息”,在另一个文件中包含多个数组。

let mode = function(data) {
  data.sort(function(a, b) {
    return a - b;    
  });
  let mode = {},
  highestOccurrence = 0,
  modes = [];
  data.forEach(function(element) {
    if (mode[element] === undefined) {
      mode[element] = 1;
    } else {
      mode[element]++;
    }
    if (mode[element] > highestOccurrence) {
      modes = [element];
      highestOccurrence = mode[element];
    } else if (mode[element] === highestOccurrence) {
      modes.push(element);
      highestOccurrence = mode[element];
    }
  });
  return modes;
};

所以一开始我只是对函数进行排序,这样数字就会以正确的顺序出现。但是有人可以帮我理解其余的功能吗?

【问题讨论】:

  • 请将data1.forEach 修改为data.forEach

标签: javascript mode find-occurrences


【解决方案1】:

我添加了一些 cmets,我只能推断出您提供的代码。您可以为您的问题提供更多背景信息,例如您拥有什么样的数据以及您想要实现什么目标,并可能提供有用的示例。

let mode = function(data) {
  data.sort(function(a, b) {
    return a - b;    
  });
  let mode = {},
  highestOccurrence = 0,
  modes = [];

  // This loops through data array (It should be data here and not data1)
  data.forEach(function(element) {

    // Here you check if the mode object already have that element key,  
    // setting the first occurence or incrementing it

    if (mode[element] === undefined) {
      mode[element] = 1;
    } else {
      mode[element]++;
    }

    // After that it checks if that mode has the higher occurence

    if (mode[element] > highestOccurrence) {

      // If it has the higher occurence it sets the modes to an array with
      // that element and the highestOccurrence value to that value
      modes = [element];
      highestOccurrence = mode[element];

    } else if (mode[element] === highestOccurrence) {
      // If it has the same number of occurences it just adds that mode to
      // the modes to be returned
      modes.push(element);
      highestOccurrence = mode[element];
    }
  });
  return modes;
};

希望对你有帮助

【讨论】:

  • 例如我有这个数组:([20, 4, 1, 2, -1, 2, 13, 2, 1, 5, 5, 5, 5, 20, 20]) 和我应该创建函数来查找最大值、最小值、平均值、中值、众数和范围。不过你加的cmet确实让我明白了很多,谢谢!
  • @taguenizy ...您从未尝试过-代码应该像OP的示例一样抛出错误,因为操作data1与传递的data无关.
  • @PeterSeliger 我认为这是一个错字。他想了解它在做什么,而不是为什么它不起作用。但我会在回复中更正它
  • 它应该在两者中都显示数据,这是一个错字,我现在已经更正了。
  • 感谢您的两次编辑 - 现在可以对答案进行投票了。
猜你喜欢
  • 2019-03-12
  • 2016-10-21
  • 2011-04-21
  • 2015-04-17
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
相关资源
最近更新 更多