js 实现数组中取出现频次最大的值

前言:因项目需要,要实现常用诊断要从医生选择的频次来加载20条。

解决:

1. 医生每选一次都要存入一个数组,存到localStorage 里面 ,注意,此处要在localStorage里面添加,不是覆盖;解决如下:

利用push 和apply 方法,来实现,这样不会覆盖,也不会把重合的去掉,从而实现数组的合并;

语法:a.push.apply(a,b);        a、b 都为数组 

this.checkedNames.push.apply(this.checkedNames,JSON.parse(localStorage.getItem('commom_JY')));

2. 从数组里面把出现频次最多的那几项找出来;用es6 语法 。此项目是把前20条取出来,例子如下:

function f(arr){
    class num{
        constructor(value){
            this.value=value;
            this.index=1;
        }
        add(){
            this.index++;
        }
    }
    arr.sort();
    let temp=[];
    temp[0]=new num(arr[0]);
    for(let i=1;i<arr.length;i++){
        if(arr[i]==arr[i-1]){
            temp[temp.length-1].add();
        }else{
            temp.push(new num(arr[i]));
        }
    }
    temp.sort(function(a,b){
        return a.index<b.index;
    });
    let temp_length=temp.length;
    if(temp_length>20){
        temp_length=20;
    }
    var common_zd=[];
    function obj(index,value) {
        this.index=index;
        this.value=value;
    }
    for(let i=0;i<temp_length;i++){
        common_zd.push({
            templateContent:temp[i].value,
            unique:i
        });
    }
    console.log(common_zd);
}

var arr=['a','b','a','b','a','c','d','d','d','d','窦性心律','窦性心律','窦性心律','窦性心律','窦性心律','ST','ST','ST','ST','ST','ST','ST','ST','ST'];
f(arr);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值