1

I am trying to find the lowest value of arrayvals[i] and set it to lowest. However, I can only seem to figure out how to accomplish this by initializing lowest to a number highest than all the lows. Is there an different way of accomplishing this? I feel like the solution is quite simple, but for some reason I can't figure it out.

function main() {
    const WEEK_WEATHER = {
        monday: { low: 61, high: 75 },
        tuesday: { low: 64, high: 77 },
        wednesday: { low: 68, high: 80 },
        thursday: { low: 64, high: 80 },
        friday: { low: 68, high: 90 },
        saturday: { low: 62, high: 81 },
        sunday: { low: 70, high: 86 }
    };
    //Display all weather:
    const { monday, tuesday, wednesday, thursday, friday, saturday, sunday } = WEEK_WEATHER;
    const arrayvals = [monday, tuesday, wednesday, thursday, friday, saturday, sunday];
    let day = 1;
    let highest = 0;
    let lowest = 1000; //Initialized higher than all lows
    for (let i in arrayvals) {
        console.log(`Day: ${day++} | Low: ${arrayvals[i].low} | High: ${arrayvals[i].high}`);

        if (arrayvals[i].low < lowest) {
            lowest = arrayvals[i].low;
        } //Current check condition

        if (arrayvals[i].high > highest) {
            highest = arrayvals[i].high;
        }
    }
    console.log("Lowest: " + lowest + " | highest: " + highest);

}
main();

Hoping to find an alternative way to solve this issue.

  • Are you after only the lowest or both lowest and highest? – Phil Mar 29 '23 at 01:48
  • 1
    Does this answer your question? [Find the min/max element of an array in JavaScript](https://stackoverflow.com/questions/1669190/find-the-min-max-element-of-an-array-in-javascript) – Rodrigo Rodrigues Mar 29 '23 at 01:57

3 Answers3

2

You can get both the lowest and highest temperature in a single reduce() operation.

If you don't seed reduce() with an initial value, it will take the first value from the array, so no need to initialize with Infinity or -Infinity.

const WEEK_WEATHER = {
    monday: { low: 61, high: 75 },
    tuesday: { low: 64, high: 77 },
    wednesday: { low: 68, high: 80 },
    thursday: { low: 64, high: 80 },
    friday: { low: 68, high: 90 },
    saturday: { low: 62, high: 81 },
    sunday: { low: 70, high: 86 }
};

const result = Object.values(WEEK_WEATHER).reduce((a, {low, high}) => ({
  low: Math.min(a.low, low),
  high: Math.max(a.high, high)
}));

console.log(result);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

I'm not a big fan of using reduce so I think you could also do like this

const lowest = Math.min(...arrayvals.map(d => d.low))
Ikhyeon Kim
  • 171
  • 5
0

This will get the lowest value

const lowest = arrayvals.reduce((acc, val) => val.low < acc ? val.low : acc, Infinity)
Ayudh
  • 1,673
  • 1
  • 22
  • 55