Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find lowest i value while iterating through array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading