按键值对数据进行排序

时间:2020-05-22 16:00:43

标签: 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,

[...]

   "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

这可能吗?

非常感谢您的阅读!

2 个答案:

答案 0 :(得分:2)

假设您的数据位于json文件中,则可以使用readFileSync读取数据,然后执行下面实现的findHighest功能:

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));

请注意,此解决方案只会根据需要提供第一个结果,并且避免了排序,因为我们基本上只迭代一次,因此运行时间更快。

答案 1 :(得分:1)

可能的解决方案是遍历键并将其存储到一个变量,如果该变量大于当前保存的变量:

const obj = {
  "automotive_auto buying and selling_1_2": 1,
  "automotive_auto infotainment technologies_1_9_1": 3,
  "automotive_auto insurance_1_3": 5,
  "automotive_auto navigation systems_1_9_2": 1,

}

let maxKey = Object.keys(obj)[0]
for (const key of Object.keys(obj)) {
  if (obj[key] > obj[maxKey]) {
    maxKey = key
  }
}

console.log(maxKey, obj[maxKey])