gpt4 book ai didi

javascript - 计算 javascript 对象中的出现次数

转载 作者:行者123 更新时间:2023-12-03 10:52:19 25 4
gpt4 key购买 nike

对象{绿色:3,红色:2,蓝色:1,黄色:1,薄荷色:3}

我想循环遍历这个对象并返回数组中出现次数最多的键(按值)。在本例中,它将是薄荷色和绿色,如 ["mint", "green"]

到目前为止,我得到了这个

for (var i = 0; i < key(obj).length; i++) {
... // no idea
}

任何帮助或指导表示赞赏。谢谢!

最佳答案

var obj = {"green": 3, "red": 2, "blue": 1, "yellow": 1, "mint": 3},
keys = Object.keys(obj), // get all keys as array
max = Math.max.apply(Math, keys.map(function(key) { return obj[key]; })), // find the biggest number of occurrences
result;

result = keys.filter(function(key) { // find the relevant keys
return obj[key] == max;
});

console.log(result);

关于javascript - 计算 javascript 对象中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28388690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com