javascript - 了解查找众数的函数

标签 javascript mode find-occurrences

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

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

所以首先我只是对函数进行排序,以便数字将以正确的顺序出现。但是有人能帮我理解这个函数的其余部分吗?

最佳答案

我添加了一些注释,我只能推断是您提供的代码。您可以为您的问题提供更多背景信息,例如您拥有的数据类型以及您想要实现的目标,也许还可以提供有用的示例。

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

希望这对你有帮助

关于javascript - 了解查找众数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39570066/

相关文章:

apache-spark - spark独立模式和本地模式的区别?

三星 Galaxy S 上的 Android 开发

java - 如何计算并仅打印重复项?

python - 打印字符串中多次出现的情况

javascript - 数据属性与 Knockout 的双向绑定(bind)

javascript - 使用 Javascript 在 Node.js 中对文本内容执行多个正则表达式过滤器

javascript - 循环遍历 JSON 数组以获取 JavaScript 中的特定数据

c - 防止退出最大化窗口模式

awk - 删除第一次和最后一次出现列值的行

javascript - ESLint 正在读取其他配置