如何从JavaScript对象数组中获取指定字段值最大的对象
Great job figuring out how to get the maximum DisplayAQI value already! To grab the actual object that holds this max value, here are a couple of straightforward approaches:
Basic Two-Pass Method
Since you already know how to calculate the max value, you can use Array.find() to pick out the first object in your list that matches that value:
// First get the max value as you already do const maxAQI = Math.max.apply(Math, list.map(o => o.DisplayAQI)); // Then find the corresponding object const maxAQIObject = list.find(o => o.DisplayAQI === maxAQI);
This is super easy to read and understand, though it does loop through the array twice (once for the map, once for the find). For small to medium-sized arrays, this works perfectly fine.
Efficient Single-Pass Method
If you want to optimize for larger arrays (or just prefer doing it in one go), use Array.reduce(). This method iterates through the array once, keeping track of the object with the highest DisplayAQI as it goes:
const maxAQIObject = list.reduce((currentMax, obj) => { return obj.DisplayAQI > currentMax.DisplayAQI ? obj : currentMax; }, list[0]); // Start with the first object as the initial "max"
Quick Notes:
- If multiple objects have the same maximum DisplayAQI value, both methods will return the first occurrence of that value in the array.
- Don’t forget to handle empty arrays! Add a check like
if (list.length === 0) { /* handle empty case here */ }to avoid errors if your list might be empty.
内容的提问来源于stack exchange,提问作者americanslon

