找出数组中出现次数最多的元素,这个解法有 bug

var each = [].forEach;
function search(arr) {
  var counts = {};

  each.call(arr, val => {
    if (counts[val] === void 0) {
      counts[val] = 0;
    }
    counts[val]++;
  });

  var maxCount = counts[arr[0]];
  var maxNumber = 0;

  each.call(arr, val => {
    if (counts[val] > maxCount) {
      maxCount = counts[val];
    }
  });

  each.call(arr, val => {
    if (counts[val] === maxCount) {
      maxNumber = val;
    }
  });

  return maxNumber;
}

标签: none

仅有一条评论

  1. 这种方式还有个局限,就是必须要数据的类型能够成为 JSON 的 Key,针对复杂数据类型可以提供 getKey 类似的函数钩子来实现 Compare

添加新评论