Arrays 按键值排序数据
我有一个JSON文件:Arrays 按键值排序数据,arrays,json,Arrays,Json,我有一个JSON文件: { "automotive_auto buying and selling_1_2":2.66883E-06, "automotive_auto infotainment technologies_1_9_1":8.67917E-06, "automotive_auto insurance_1_3":1.41038E-06, "automotive_auto navigation systems_1_9_2":1.13127E-05, [...]
{
"automotive_auto buying and selling_1_2":2.66883E-06,
"automotive_auto infotainment technologies_1_9_1":8.67917E-06,
"automotive_auto insurance_1_3":1.41038E-06,
"automotive_auto navigation systems_1_9_2":1.13127E-05,
[...]
"video gaming_simulation video games_29_5_11":3.81729E-06,
"video gaming_sports video games_29_5_12":2.02059E-06,
"video gaming_strategy video games_29_5_13":3.41502E-07
}
我需要一个JavaScript函数以降序排列这些数字,并获取数字最大的键,这里首先给出:
1.13127e-05
8.67917e-06
3.81729e-06
2.66883e-06
2.02059e-06
1.41038e-06
3.41502e-07
因此我会得到第一个结果的对应键:
automotive_auto navigation systems_1_9_2
这可能吗
非常感谢你的阅读 可能的解决方案是循环键,如果大于当前保存的值,则将其存储到变量中:
const obj={
“汽车买卖”:1,
“汽车信息娱乐技术”3、,
“汽车保险”:5,
“自动导航系统”:1,
}
设maxKey=Object.keys(obj)[0]
for(对象的常量键。键(obj)){
if(obj[key]>obj[maxKey]){
maxKey=key
}
}
console.log(maxKey,obj[maxKey])
假设您的数据位于json文件中,您可以使用readFileSync
读取数据,然后执行下面实现的findhigest
功能:
const fs = require("fs");
let jsDataArray = Object.entries(
JSON.parse(fs.readFileSync(`${__dirname}/file.json`, "utf8"))
);
const findHighest = (data) => {
let result = data[0][1];
let finalResult = data[0][0];
data.forEach((item) => {
if (item[1] > result) {
result = item[1];
finalResult = item[0];
}
});
return finalResult;
};
console.log(findHighest(jsDataArray));
请注意,此解决方案只提供您想要的第一个结果,并且避免了排序,因为我们基本上只迭代一次。欢迎使用堆栈溢出!请拿着(你得到了一枚徽章!)通读一下,尤其是你最好的选择是做你的研究,做相关的主题,然后试一试。如果你在做了更多的研究和搜索后陷入困境,无法摆脱困境,请发布一份你的尝试,并明确指出你陷入困境的地方。人们会乐于帮助的。这就是我所描述的问题的解决方案。非常感谢你。然而,我想指出的是,我最终使用了@zirmax的解决方案,因为我意识到它更适合我的具体情况。这是我最终使用的解决方案,尽管要解决我的确切问题,请注意@David Prifti的答案。非常感谢你们两位!