【问题标题】:How can I find highest and lowest in an array of objects/ Javascript如何在对象/ Javascript 数组中找到最高和最低
【发布时间】:2021-03-27 06:02:22
【问题描述】:

我是 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]}
]

【问题讨论】:

  • 这感觉像是一道作业题,所以我希望没有人会直接给你答案,而是会帮助你自己找到答案。您的内部循环正在使用weather.length,鉴于每个月的温度值数量与月数不同,这可能无法达到您的预期。一旦你得到了每个月的正确平均值,你就需要找到这些平均值的最小值,以及这些平均值的最大值。你怎么能这样做?

标签: javascript arrays object average


【解决方案1】:

我对对象进行了变异,并在对象本身中添加了lowest、“最高”和“平均”。

为了获得monthtemperature,我使用了object destructuring

然后使用sort函数对数组进行排序。

现在 tempArray 已排序,索引 0 处的元素是 lowesttemporary.length - 1 处的元素是`最高元素。

为了获得数组的平均值,我使用了数组 reduce 函数。

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);

【讨论】:

  • 非常感谢,但问题是获取和分析平均月份中的最高和最低。就像最热和最冷的月份。我怎么才能得到它?我应该使用 for in 吗?
  • @RoyFied 更新了代码,平均月份中最低和最高。这是你问的吗
  • 没错!非常感谢你!你帮了我很多
【解决方案2】:

使用 map 和 reduce。在地图回调中使用 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)

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2022-01-05
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多