javascript - 变体:在Javascript中找到value最高的对象

https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects 中,有许多(很棒的)答案报告了数组中最高的 value,但他们遗漏了以下选项具有最高 value 的对象将是报告所需的结果。

我正在寻找搜索数组中最高的 value 并返回具有此 value 的对象的最佳方法。例如,检查这个数组的预期结果:

{
      "Intent": {
        "FileComplaint": 0.000,
        "UnsubscribeMe": 0.995,
        "TrackRefund": 0.001,
        "AskSwitchAccount": 0.00
      }

将是:“UnsubscribeMe”或“UnsubscribeMe”:0.995。

谁能帮忙?

编辑:我发现了一个比我的问题表述得更好的问题,它有很好的答案:https://stackoverflow.com/questions/27376295/getting-key-with-the-highest-value-from-object

回答1

const obj={Intent:{FileComplaint:0,UndermineGovernment:0.45,UnsubscribeMe:.995,TrackRefund:.001,AskSwitchAccount:0}};

// Get the entries as a nested array of key/value pairs
const entries = Object.entries(obj.Intent);

// Sort the entries by value (index 1),
// and then pop off the last entry destructuring
// the key/value from that array in the process
const [key, value] = entries.sort((a, b) => a[1] > b[1]).pop();

// Log the resulting object
console.log({ [key]: value });

相似文章

随机推荐

最新文章