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?
CodePudding user response:
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 });
CodePudding user response:
I found a question that is better formulated than mine and it has great answers: