Start learning free

LESSON 273 OF 675 · TUPLES, SORTING & BUILT-INS

Min, Max and Sum in TypeScript: Math.min, Math.max and reduce

Lesson Read the full explanation

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 = 235
STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · TUPLES, SORTING & BUILT-INS

    Min Max Sum in TypeScript, explained

    Ready-made tools

    Finding the smallest value, the largest value and the total of an array come up all the time. You can write a loop for each, but TypeScript has ready-made tools:

    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
    

    Math.min and Math.max with the spread dots

    Math.min and Math.max compare separate numbers, as in Math.max(3, 8), which is 8. They don't take an array. The three dots in ...prices are the spread syntax: they spread the array out into separate arguments, so Math.max(...prices) means Math.max(4, 9, 2, 7).

    Don't forget the dots. Math.max(prices) is reported by the compiler as an error, because the function expects a number and gets an array. tsc still writes the JavaScript, and when it runs, a four-item array in that spot gives NaN.

    Adding up with reduce

    There is no ready-made sum function. The array method reduce does the job:

    let total = prices.reduce((sum, x) => sum + x, 0);
    

    The arrow function receives the running sum and the next value x, and returns the new sum. reduce calls it once per value, from left to right. The 0 at the end is where the sum starts, and TypeScript works out that both sum and x are numbers. For [4, 9, 2, 7] the sum goes 0, 4, 13, 15, 22.

    Watching reduce work

    With the exercise's minutes, [25, 40, 15, 60, 30, 45, 20], the running sum after each day is 25, 65, 80, 140, 170, 215 and 235. The last value is what reduce returns. Each call to the arrow function gets the previous result as sum and the next day as x. The same method can do more than add: minutes.reduce((best, x) => (x > best ? x : best), minutes[0]) finds the largest value, 60. For plain maximums, though, Math.max(...minutes) is clearer.

    The empty array

    • Math.max(...[]) is -Infinity and Math.min(...[]) is Infinity. There is no error, just a strange number. Check arr.length first when the array might be empty.
    • reduce on an empty array with the start value gives that start value, 0. Without the start value, it throws a TypeError ("Reduce of empty array with no initial value"). So always pass the 0.

    Where else the dots work

    Spread is not only for Math.min and Math.max. It can also copy an array into a new one: [...minutes] is a separate array with the same values, which is handy when you want to sort without changing the original. And you can use it to join arrays, as in [0, ...minutes].

    The average

    With the total in hand, the average is the total divided by the count: total / minutes.length. For the exercise's week that is 33.57142857142857, because division in TypeScript gives a decimal. None of these tools change the array: after the calls, minutes still holds all seven values.

    The exercise

    minutes holds how many minutes you practiced on each day of a week. Store the shortest day in shortest, the longest in longest, and the week's total in total. The code at the bottom prints all three.

    1. Math.min(...minutes) for shortest.
    2. Math.max(...minutes) for longest.
    3. minutes.reduce((sum, x) => sum + x, 0) for total.
    let minutes: number[] = [25, 40, 15, 60, 30, 45, 20];
    let shortest: number = Math.min(...minutes);
    let longest: number = Math.max(...minutes);
    let total: number = minutes.reduce((sum, x) => sum + x, 0);
    console.log("shortest = " + shortest);
    console.log("longest = " + longest);
    console.log("total = " + total);
    

    It prints:

    shortest = 15
    longest = 60
    total = 235
    

    Key takeaways

    • Math.min(...arr) and Math.max(...arr) need the spread dots.
    • arr.reduce((sum, x) => sum + x, 0) adds up an array; keep the start value.
    • An empty array gives Infinity, -Infinity or a TypeError, so check its length when it can be empty.
    Keep going with TypeScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free