简体   繁体   English

如何在对象数组/ Javascript 中找到最高和最低

[英]How can I find highest and lowest in an array of objects/ Javascript

I am new in js, can u help me finding the highest and lowest temperature in array of objects我是 js 新手,你能帮我找到对象数组中的最高和最低温度吗

let weather = [
  { month: 'March',   temperature: [2,5,4,3,7,12]},
  { month: 'April', temperature: [14,15,16,19, 20]},
  { month: 'May',   temperature: [22,24,26,28,27]}
]

I've mutated the object and added lowest , 'highest', and 'average' in the object itself.我已经对 object 进行了变异,并在 object 本身中添加了lowest 、“最高”和“平均”。

To get the month and temperature , I've used object destructuring .为了得到monthtemperature ,我使用了 object 解构

Then sort the array using sort function.然后使用sort function 对数组进行排序。

Now the tempArray is sorted and the element at index 0 is the lowest and the element at temporary.length - 1 is the `highest element.现在 tempArray 已排序,索引0处的元素是lowest的, temporary.length - 1处的元素是“最高元素”。

To get average of an array, I've used the array reduce function.为了得到一个数组的平均值,我使用了数组reduce function。

 let weather = [ { month: "March", temperature: [2, 5, 4, 3, 7, 12] }, { month: "April", temperature: [14, 15, 16, 19, 20] }, { month: "May", temperature: [22, 24, 26, 28, 27] }, ]; let getAverage = (array) => array.reduce((a, b) => a + b) / array.length; weather.forEach((monthData) => { const { month, temperature } = monthData; // temporary sorted array const tempArray = [...temperature].sort((a, b) => a - b); // Lowest monthData.lowest = tempArray[0]; // Heighest monthData.highest = tempArray[tempArray.length - 1]; // Average monthData.average = getAverage(tempArray); }); console.log(weather); const averageArray = weather.map((month) => month.average).sort((a, b) => a - b); const lowestInAverage = averageArray[0]; const highestInAverage = averageArray[averageArray.length - 1]; console.log(lowestInAverage, highestInAverage);

Use map & reduce.使用 map 并减少。 Inside map callback use Math.max & Math.min to find highest and lowest temperature and use sort to sort the array by ascending order of average temperature在 map 回调中使用 Math.max 和 Math.min 查找最高和最低温度,并使用 sort 按平均温度升序对数组进行排序

 let weather = [{ month: 'March', temperature: [2, 5, 4, 3, 7, 12] }, { month: 'April', temperature: [14, 15, 16, 19, 20] }, { month: 'May', temperature: [22, 24, 26, 28, 27] } ] const val = weather.map(item => { return { month: item.month, temperature: item.temperature, lowest: Math.min(...item.temperature), highest: Math.max(...item.temperature), avgTemp: item.temperature.reduce((acc, curr) => { return (acc + curr) }, 0) / item.temperature.length } }).sort((a, b) => a.avgTemp - b.avgTemp) console.log(val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM