我有一个对象包含一些类别作为键,然后一个整数作为属性:
{
thing1: 12,
thing2: 32,
thing3: 9,
thing4: 2
}
我需要找到所有数字中的模式(最高数字 - 在这种情况下为32),然后返回密钥。最好的方法是什么?
答案 0 :(得分:1)
这是我要采取的一种方式:
// Helper function to get values from an object
function values(obj) {
return Object.keys(obj).reduce(function(result, nextVal) {
result.push(obj[nextVal]);
return result;
}, []);
}
function getMode(obj) {
var maxVal = Math.max.apply(Math, values(obj));
var maxKey;
Object.keys(obj).forEach(function(key) {
if(obj[key] === maxVal) {
maxKey = key;
}
});
return maxKey;
}
用法:
getMode(obj);
//=> "thing2"