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
This will get the lowest value
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 withInfinity
or-Infinity
.I’m not a big fan of using
reduce
so I think you could also do like this