skip to Main Content

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.

3

Answers


  1. This will get the lowest value

    const lowest = arrayvals.reduce((acc, val) => val.low < acc ? val.low : acc, Infinity)
    
    Login or Signup to reply.
  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);
    Login or Signup to reply.
  3. 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))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search