求已知数组对象中,重复次数最多及最少的元素及重复次数?

有没有简单一点的写法,现在只能求出最多元素,如果最少元素也想展示出来应该怎么改?

 let array=['1','3','4','3','5','5','5','5','1'];
    function A(arr){
        let map=new Map();
        let key=array[0],
            value=1;
        arr.forEach((item)=>{
            if(map.get(item)!==undefined){
                let num=map.get(item);
                map.set(item,++num);
            }else{
                map.set(item,1);
            }
            if (map.get(item) > value) {
                key = item;
                value = map.get(item);
            }
        });
        console.log(key,value);
    }
    A(array);
阅读 4.1k
5 个回答

思路是一样的,你求最大时,假定最大初始值是 0,之后遍历以后,发现只要大于当前最大值就重新赋值最大值。

那求最小值也一样啊,直接假定最小初始值是 Map 中的第一个值,然后遍历,只要比这个最小值小的,那就重新赋值最小值。

另外,判定 Map 中有没有某个 key,可以使用 Map.prototype.has,少码几个字,可以早点下班回家。


updated

鉴于大家都履行 talk is cheap,show me the code 的原则,所以我也抽空实现一版,感觉是有点小 bug 的,仅供参考:

function minAndMaxCount(arr = []) {
  const l = arr.length
  return arr.reduce((a, c, i) => {
    if (a[c]) a[c] += 1
    else a[c] = 1

    if (i < l - 1) {
      return a
    } else {
      return Object.keys(a).reduce(
        (ca, cc) => {
          ca.min = Math.min(ca.min, a[cc])
          ca.max = Math.max(ca.max, a[cc])
          return ca
        },
        {
          min: Infinity,
          max: -Infinity
        }
      )
    }
  }, {})
}

这里我默认传入数组都是 number[] 类型的了,如果要直接用的话,记得转换一下类型,运行结果:

clipboard.png

function demo (arr) {
  let numMap = {}
  let statistics = [];
  arr.forEach(num => numMap[num] = (Number(numMap[num]) || 0) + 1)
  for(let key in numMap) {
    statistics.push({
      key,
      count: numMap[key]
    })
  }
  statistics.sort((a, b) => a.count < b.count ? 1 : -1)
  return {
    max: statistics[0],
    min: statistics[statistics.length-1]
  }
}


var res = demo(['1','3','4','3','5','5','5','5','1'])
console.log(JSON.stringify(res)) // => {"max":{"key":"5","count":4},"min":{"key":"4","count":1}}

如果存在多个次数最多/最少的元素,也可以取出

 let array = ['1', '3', '4', '3', '5', '5', '5', '5', '1', '1', '1'];

 function A(arr) {
     let map = new Map();
     arr.forEach((item) => {
         if (map.has(item)) {
             let num = map.get(item);
             map.set(item, ++num);
         } else {
             map.set(item, 1);
         }
     });

     let max = 1;
     let min = map.entries().next().value[1];
     map.forEach((value, key) => {
         if (value > max) {
             max = value;
         }
         if (value < min) {
             min = value;
         }
     });
     console.log(getByValue(map, max));
     console.log(getByValue(map, min));
 }

 // 根据value取key
 function getByValue(map, searchValue) {
     let keys = [];
     for (let [key, value] of map.entries()) {
         if (value === searchValue)
             keys.push(key);
     }
     return keys;
 }
 A(array);
const rank = (items = []) => {
  const counter = new Map();
  for (const item of items) {
    counter.set(item, (counter.get(item) || 0) + 1);
  }
  return Array.from(counter)
    .map(([key, count]) => ({ count, key }))
    .sort(({ count: m }, { count: n }) => m - n);
};

const result = rank(["1", "3", "4", "3", "5", "5", "5", "5", "1"]);

console.log(result);

const min = result[0].key,
  max = result[result.length - 1].key;

console.log(min, max);
    let array = ["1", "3", "4", "3", "5", "5", "5", "5", "1"];
    let a = array.reduce((prev, current) => {
        let obj = {
            name: current,
            count: 0
        };
        let inx;
        let flag = prev.length !== 0 && prev.some((item, index) => {
                inx = index;
                return item.name == current;
            });
        if (flag) {
            prev[inx].count++;
        } else {
            obj.count++;
            prev.push(obj);
        }

        return prev;
    }, []);

    a.sort(function(a, b) {
        return a.count - b.count; //升序
    });
    console.log(a);
    console.log("出现次数最多的:" + a[a.length - 1].name);
    console.log("出现次数最少的:" + a[0].name);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题