TL ; DR:
Math.min(...arr) gives the smallest value of an array.
Math.max(...arr) gives the largest value.
reduce adds all the values up.
let prices = [4, 9, 2, 7];
console.log(Math.min(...prices)); // 2
console.log(Math.max(...prices)); // 9
let total = prices.reduce((sum, x) => sum + x, 0);
console.log(total); // 22
Full lesson:
In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. TypeScript has ready-made tools for them.
Math.min and Math.max compare separate numbers, as in Math.max(3, 8). You used Math.max this way in Maximum Number In Array. The three dots in ...prices spread the array out into separate numbers. So Math.max(...prices) is the array's largest value.
Don't forget the dots. TypeScript won't compile Math.max(prices). It expects numbers, not an array.
TypeScript has no sum function. The array method reduce does the job:
let total = prices.reduce((sum, x) => sum + x, 0);
The arrow function gets the running sum and the next value x. It returns the new sum. TypeScript works out that both are numbers. The reduce method calls it once per value, from left to right. The 0 at the end is where the sum starts.
Watch out for an empty array. Math.max(...[]) is -Infinity. Math.min(...[]) is Infinity. You get no error, just a strange number. Check arr.length first.
reduce on an empty array gives its start value, 0. Without that 0, it throws a TypeError. So always pass it.
Your task
minutes holds how many minutes you practiced coding on each day of a week.
Store the shortest day in shortest and the longest day in longest. Store the week's total in total.
Use the built-ins from this lesson. The code at the bottom prints all three.
Expected output:
shortest = 15
longest = 60
total = 235Free plan: 30 tutor messages. PRO is unlimited.
