-2

In Finding the max value of an attribute in an array of objects there are many (great) answers that report the highest value in an array, but they leave out the option that the object with the highest value would be the desired result to report.

I'm looking for the best way to search for the highest value in an array and return the object that has this value. For example, the expected result of checking this array:

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

would be: "UnsubscribeMe" or "UnsubscribeMe": 0.995.

Anyone who can help?

Edit: I found a question that is better formulated than mine and it has great answers: Getting key with the highest value from object

Nas
  • 17
  • 6
  • The answer is in the link you posted. – Grumpy May 14 '22 at 14:43
  • 1
    You only have objects at this point, no arrays. – Andy May 14 '22 at 14:44
  • @Grumpy I assume you refer to the posts (currently) at the bottom; but they miss to include the variable in the results because they strip everything to numbers. I would need the variable name as well in the result. – Nas May 14 '22 at 14:45
  • @Andy Tx. I rephrased. – Nas May 14 '22 at 14:47
  • 1
    what if you have more than one property with same max value? – Nina Scholz May 14 '22 at 14:49
  • You just need to sort the array descending, then pick the first element. Also, why would you need the name of the prop? You either pass it in or hardcode it, so you already have it. –  May 14 '22 at 14:51
  • @NinaScholz Good point. For my use case it doesn't matter, but I can imagine that there are cases where it does... – Nas May 14 '22 at 15:21
  • @ChrisG Yeah I thought about that approach as well, but I didn't know how to order when the objects have values. I need the name because I use a tool in which I can leave some javascript but not pass on the names. I'm clearly not a guru programmer. – Nas May 14 '22 at 15:25
  • Wait, the array you were talking about is actually the object above? I thought that was just one example of the objects in the array. –  May 14 '22 at 16:48

1 Answers1

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 });
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    Thanks a lot @Andy ! I love your genius little twist with the objects :-) – Nas May 14 '22 at 15:19
  • 1
    Note @Nas it's worth bearing Nina's comment in mind as this answer doesn't cover that eventuality. – Andy May 14 '22 at 15:21