如何获得最大数量和密钥

问题描述 投票:0回答:1

我有这样的人

hash['a'] = ["a","b","c","d","e"];
hash['b'] = ["a","b","c"];
hash['k'] = ["q","b"];

Math.max(Object.keys(hash).map(function(key){
     return hash[key].length;
});

它返回5,但是我想同时获得哈希键'a'

有可能吗?

javascript dictionary
1个回答
0
投票

这符合您的要求吗?

我在这里使用sort而不是Math.max来找到最大值

var hash = {};
hash['a'] = ["a", "b", "c", "d", "e"];
hash['b'] = ["a", "b", "c"];
hash['k'] = ["q", "b"];

var result = Object.keys(hash)
    .map(function(key) {
      return {[key]: hash[key].length};
    }).sort(function(a, b){ 
      return a.key > b.key
    })[0]
  
  
console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.