首页 > 试题广场 >

高频数据类型

[编程题]高频数据类型
  • 热度指数:5381 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
请补全JavaScript代码,要求找到参数数组中出现频次最高的数据类型,并且计算出出现的次数,要求以数组的形式返回。
注意:
1. 基本数据类型之外的任何引用数据类型皆为"object"
2. 当多种数据类型出现频次相同时将结果拼接在返回数组中,出现次数必须在数组的最后
示例1

输入

__findMostType([0,0,'',''])

输出

['number','string',2]或['string','number',2]
            评论区一个有注释的都没有 自己看了一个小时
            let obj = {};
            let num = 0;
            //遍历数组中每一项
            for (let i = 0; i < array.length; i++) {
                //判断每一项的数据类型
                let type = typeof (array[i])
                //判断数据类型是否出现过 出现过值就加一 没出现过就为1
                // obj[type] 默认在obj对象中添加type属性 初始值为undifine
                if (obj[type]) {
                    obj[type]++
                } else {
                    obj[type] = 1
                }
                //选出出现频率次数最高的值 给num
                //大于 保留boj[type]的值 不大于保留原来的值
                num = obj[type] > num ? obj[type] : num
            }
            let arr = [] //接受出现频率次数最多的数据类型
            for (key in obj) {
                if (obj[key] === num) {
                    arr.push(key)
                }
            }
            return [...arr, num]
发表于 2022-04-19 16:35:49 回复(3)
Object.values不识别
发表于 2022-07-15 15:54:45 回复(1)
        <script type="text/javascript">
            const _findMostType = array => {
                // 补全代码
                // 存放结果的数组
                let arr = [];
                // 对象,数据类型为键名,键值为数据类型出现的次数
                let o = {};
                // 出现次数最多数据类型的次数
                let maxnum = 0;
                // 遍历数组
                array.forEach(item => {
                    // 获取数据类型 -- 基本数据类型、object类型
                    let type = (typeof item) ? (typeof item) : 'object';
                    o[type] = o[type] ? o[type] + 1 : 1;
                    maxnum = maxnum > o[type] ? maxnum: o[type];
                })
                // 生成返回数组
                Object.keys(o).forEach(key => {
                    if(o[key] === maxnum){
                        arr.push(key);
                    }
                })
                arr.push(maxnum);
                return arr;
            }
        </script>

发表于 2022-03-22 17:16:23 回复(0)

代码并不复杂,原理是【对象key的唯一性

将类型值作为对象的key,然后将出现的次数作为对象的value

最后统计出现次数最多的key就可以了
let obj = {},
  result = [],
  num = 0;

array.map(item => {
  let type = typeof (item);

  obj[type] = (obj[type] || 0) + 1

  num = Math.max(obj[type], num)
})

for (let key in obj) {
  result = obj[key] == num ? [...result, key] : result
}

return [...result, num]



发表于 2023-03-28 16:14:05 回复(0)
const _findMostType = array => {
    // 补全代码
    let o = {}, arr = [], maxNum = 0;
    array.forEach(item => {
        let type = item === null ? 'null' : (typeof item === 'function' ? 'object' : (typeof item));
        o[type] = o[type] ? o[type] + 1 : 1;
        maxNum = o[type] > maxNum ? o[type] : maxNum;
    });
    Object.keys(o).forEach(key => {
        if(o[key] === maxNum){
            arr.push(key);
        }
    })
    arr.push(maxNum);
    return arr;
}

发表于 2021-12-28 14:12:41 回复(0)
          let counts = {};
  let maxCount = 0;
 
  // 统计各个数据类型的出现次数
  array.forEach(item => {
    let type = typeof item;
    if (type === 'object') {
      type = item === null ? 'null' : 'object';
    }
    if (counts[type]) {
      counts[type]++;
    } else {
      counts[type] = 1;
    }
    maxCount = Math.max(maxCount, counts[type]);
  });

  let result = [];
 
  // 找到出现次数最多的数据类型
  for (let type in counts) {
    if (counts[type] === maxCount) {
      result.push(type);
    }
  }
 
  // 将出现次数拼接在数组末尾
  result.push(maxCount);
 
  return result;
发表于 2024-03-29 09:57:41 回复(0)
const _findMostType = array => {
              // 补全代码
              const obj = {}
              array.forEach(item => {
                const type = item === null ? 'null' : typeof item
                const bool = Object.hasOwn(obj, type)
                if(bool){
                  obj[type] += 1
                }else{
                  obj[type] = 1
                }
              })
              const max = Math.max(...Object.values(obj))
              const result = Object.keys(obj).filter(item => obj[item] === max)
              return [...result, num]
          }
编辑于 2024-03-17 23:43:05 回复(0)
const _findMostType = array => {
    // 补全代码
    const res = {};
    array.forEach((item) => {
        const type = typeof item === 'object' ? (item === null ? 'null' : 'object') : typeof item;
        res[type] = (res[type] ?? 0) + 1;
                     });
    return Object.entries(res).reduce(
        (res, cur) => {
            if (cur[1] > res.at(-1)) {
                res = [...cur];
            } else if (cur[1] === res.at(-1)) {
                res.unshift(cur[0]);
            }
            return res;
        },
        [0]
    );
}

编辑于 2024-03-14 23:13:34 回复(0)
const _findMostType = array => {
    // 补全代码
    const stats = {};
    // typeof null为object,需要单独处理null
    array.forEach(item => {
        let type = typeof item;
        if(item === null) {
            type = 'null';
        }
        if(item instanceof Object) {
            type = 'object';
        }
        if(!stats[type]) {
            stats[type] = 1;
        } else {
            stats[type] += 1;
        }
     });
    const nums = Object.values(stats).sort((a,b) => b -a)[0];
    const arr = Object.keys(stats).filter(type => stats[type] === nums).map(type => type);
    arr.push(nums);
    return arr;
}                


编辑于 2023-12-22 12:48:32 回复(0)
有坑:Object.values 不识别
const _findMostType = array => {
    const count = {}
    let most = 0

    for (let item of array) {
        let key = typeof item
        count[key] = (count[key] || 0) + 1
        most = count[key] > most ? count[key] : most
    }

    // 因为 Object.values 导致不通过
    // let most = Math.max(...Object.values(count))
    
    let ans = []
    for (let key in count) {
        if (count[key] === most) {
            ans.push(key)
        }
    }
    return [...ans, most]
}


发表于 2023-11-22 01:23:35 回复(0)

// 跑起来到能达到要求,但是没有通过,就是简单的循环加判断 
const _findMostType = array => {
                // 补全代码
                let ar = []
                array.forEach((item,index) => {
                    
                    
                        let a = ar.findIndex(item2=> typeof item == item2.name)
                        console.log(a);
                        if(a != -1) {
                             ar[a].num += 1
                        }else {
                            ar.push({
                                name:typeof item,
                                num:1
                            })
                        }
        
                })
                
                let indexArr = []
                let arx = []
                ar.forEach((item,index)=>{
                    let arx2 = []
                    if(indexArr.indexOf(index) == -1) {
                        ar.forEach((item2,index2)=> {
                            if(item.num == item2.num) {
                                indexArr.push(index2)
                                arx2.push(item2.name)
                                
                            }
                        })
                        
                        arx2.push(item.num)
                        arx.push(arx2)
                    }
                    
                    
                    
                })

            return arx
            
            }
            console.log(_findMostType([1, '2', [], 25,45, true, false,true,null,'sadqw',true,5888]));
发表于 2023-10-27 15:23:25 回复(0)
const _findMostType = array => {
    // 补全代码
    let temp = {} // 存储数据类型和频次
    let arr = [] // 存返回结果
    let num = 0  // 存出现的最高次数

    for (key of array) {
        let type = typeof key;
        temp[type] = temp[type] ? ++temp[type] : 1;
        num = Math.max(temp[type], num);
    }

    for (key in temp) {
        arr = temp[key] === num ? [...arr, key] : arr;
    }

    return [...arr, num]
}

发表于 2023-09-05 16:30:30 回复(0)

代码实现了统计每种类型的数量,最后根据给定情况分出现次数相同与出现次数不相同,返回对应结果,与给定题目不同的是,我将Object类型进行了统计。

const _findMostType = array => {
        // 补全代码
        let result = array
            .map(item => typeof item)
            .sort()

        let judgeArray = [...new Set(result)]
            .map(item => result.lastIndexOf(item) - result.indexOf(item) + 1)

        if ([...new Set(judgeArray)].length === 1){
            let sum = judgeArray.reduce((acc,cur) => acc = acc + cur,0)
            return [...new Set(result),sum]
        }else{
            let max = judgeArray.reduce((acc,cur) => {
                if(acc<cur) acc = cur
                return acc
            },0)
            return [...new Set(result),max]
        }
    }
发表于 2023-09-04 21:49:35 回复(0)
<!-- 请补全JavaScript代码,要求找到参数数组中出现频次最高的数据类型,并且计算出出现的次数,要求以数组的形式返回。
注意:
1. 基本数据类型之外的任何引用数据类型皆为"object"
2. 当多种数据类型出现频次相同时将结果拼接在返回数组中,出现次数必须在数组的最后 -->
<!DOCTYPE html>
<html>


<head>
    <meta charset=utf-8>
</head>

<body>

    <script type="text/javascript">
        const _findMostType = array => {
            // 补全代码
            let kindArr = []
            let maxNum = 0
            let maxArr = []
            let dataKind = {
                number: 0,
                string: 0,
                bool: 0,
                undefined: 0,
                null: 0,
                object: 0
            }
            //循环判定每一个数据类型
            for (let i in array) {
                if (typeof array[i] in dataKind) {
                    (dataKind[typeof array[i]])++
                }
            }

            //判断最大次数
            for (let j in dataKind) {
                if (dataKind[j] >= maxNum) maxNum = dataKind[j]
            }

            for (let m in dataKind) {
                if (dataKind[m] === maxNum) {
                    kindArr.push(m)
                }
            }
            kindArr.push(maxNum)
            console.log(kindArr);
            return kindArr
        }

    </script>
</body>

</html>

发表于 2023-07-26 17:16:20 回复(0)
我在浏览器里测试没问题,但是在这里就是无法通过……

const _findMostType = array => {
    // 补全代码
    function getType(val) {
        const type = typeof val;
        if (['string', 'number', 'boolean', 'symbol'].includes(type)) {
            return type;
        }
        if (val === null) {
            return 'null';
        }
        if (val === undefined) {
            return 'undefined';
        }
        return 'object';
    }
    const typeMapper = {};
    array.forEach(v => {
        const type = getType(v);
        if (typeMapper[type]) {
            typeMapper[type]++
        } else {
            typeMapper[type] = 1;
        }
    });
    return Object.entries(typeMapper).sort((pre, next) => {
        // 排序
        return next[1] - pre[1];
    }).filter((v, idx, arr) => {
        // 排除数量不等于第一个的元素
        if (arr[0][1] !== v[1]) {
            return false;
        }
        return true;
    }).reduce((pre, cur, currentIndex, arr) => {
        // 如果是最后一个元素,则 concat, 否则只 concat 数组第一个元素
        if (currentIndex === arr.length - 1) {
            return pre.concat(cur);
        }
        return pre.concat([cur[0]]);
    }, []);
}

console.log(_findMostType([1,"1",{},{},2,3,4,3,3,"","","","",""]));
// [ 'number', 'string', 6 ] 应该符合要求


发表于 2023-07-26 01:08:46 回复(0)
let map = new Map();
      for(let a of array){
        let type = typeof a;
        if(map.has(type)){
          map.set(type,map.get(type)+1);//设置频次+1
        }else{
          map.set(type,1);
        }
      }
      let arr = [];
      function timeSort(a,b){return b-a;}//从大到小排序
      let times = Array.from(map.values()).sort(timeSort);
      let n = 1;
      for(let i=0;i<times.length-1;i++){
        if(times[i] == times[i+1]){
          n++;
        }else{
          break;
        }
      }
      let max = times[0];
      if(n>1){
        Array.from(map.keys()).forEach((item)=>{
          if(map.get(item) == max){
            arr.push(item);
          }
        })
      }
      arr.push(times[0]);
      return arr;//最大值返回

发表于 2023-05-16 13:35:11 回复(0)
    const _findMostType = array => {
            // 补全代码
            const typesArr = array.map((item) => item = typeof item);
            const count = typesArr.reduce((accumulator, currentValue) => {
                accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
                return accumulator;
            }, {});
            const resultArr = []
            for (const key in count) {
                if (Object.hasOwnProperty.call(count, key)) {
                    const element = count[key];
                    if (resultArr.indexOf(element) < 0) {
                        resultArr.unshift(key, count[key])
                    } else {
                        resultArr.splice(resultArr.indexOf(element), 0, key)
                    }
                }
            }
            return resultArr
        }
        // console.log(_findMostType([0, 0, 1, '', '', true, {}, null, undefined, false]))
        console.log(_findMostType([0, 0, '', '', true]))
为什么不行啊 🆘
发表于 2023-05-10 10:50:30 回复(0)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <script type="text/javascript">
      const _findMostType = (array) => {
        // 补全代码
        let obj = {};
        let num = 0;
        const res = array.reduce((prev, curr) => {
          let type = typeof curr
          // console.log(type);
          if(obj[type]){
            obj[type]++
          }else{
            obj[type]=1
            prev.push(type)
          }
          num = obj[type] > num ? obj[type] : num
          return prev
        }, []);
        return [...res,num]
      };
      const result = _findMostType([0, 0, "", ""]);
      console.log(result);//['number', 'string', 2]
      console.log(_findMostType([0, 0, "", "",1,"",[1,2]]));// ['number', 'string', 'object', 3]
    </script>
  </body>
</html>

发表于 2023-04-27 18:09:35 回复(0)
const _findMostType = array => {
                // 补全代码
                let result = [];
                var arr=[],num=0,str=0,boo=0,obj=0,sym=0,und=0,fun=0
                array.forEach((item,index)=>{
                            arr.push(typeof item)
                })
                arr.forEach((item1,index1)=>{            
                              if(item1=='number'){
                                num++
                              }
                              if(item1=='string'){
                                str++
                              }
                           
                            if(item1=='boolean'){
                                boo++
                              }
                              if(item1=='object'){
                                obj++
                              }
                           
                            if(item1=='symbol'){
                                sym++
                              }
                              if(item1=='undefined'){
                                und++
                              }
                              if(item1=='function'){
                                fun++
                              }
                              m= Math.max(num,str,boo,obj,sym,und,fun)
                             
                            })
                            if(num==m){
                                result.push('number')
                              }
                              if(obj==m){
                                result.push('object')
                              }
                              if(sym==m){
                                result.push('symbol')
                              }
                              if(str==m){
                                result.push('string')
                              }
                              if(und==m){
                                result.push('undefined')
                              }
                              if(fun==m){
                                result.push('function')
                              }
                              if(boo==m){
                                result.push('boolean')
                              }                
                         result.push(m)
                         return result
            }
发表于 2023-04-04 23:25:53 回复(1)
                let obj={}
                array.forEach((items,index)=>{
                    if(!obj[typeof items]){
                        obj[typeof items]=1
                    }else{
                        obj[typeof items]++
                    }
                })
                let arr=['',0];
                for (const key in obj) {
                    if(obj[key]>arr[arr.length-1]){
                        arr[arr.length-1]=obj[key]
                        arr[0]=key
                        if(arr.length>2){
                            for (let i = 2; i <= arr.length; i++) {
                                arr.splice(i-1,1)
                            }
                        }
                    }else if(obj[key]==arr[arr.length-1]){
                        arr.splice(0,0,key)
                        arr[arr.length-1]=obj[key]
                        arr[0]=key
                    }
                }
                return arr
            }

发表于 2023-01-03 21:34:33 回复(0)