TypeScript: Find the Minimum Element in an Array

1. Introduction

Arrays are a foundational data structure, and finding the minimum value within an array is a common operation. Though a simple task, implementing it helps in grasping basic array manipulations and iteration concepts. In this post, we'll craft a TypeScript function to extract the smallest number from a given array of numbers.

2. Program Overview

Our goal is to develop a function named findMin that accepts an array of numbers and returns the smallest number from that array. TypeScript's type annotations will ensure our function works with arrays of numbers specifically.

3. Code Program

// Define a function to find the minimum element in an array
function findMin(numbers: number[]): number {
    let minNumber = numbers[0]; // Start by assuming the first number is the minimum
    for (let num of numbers) {
        if (num < minNumber) {
            minNumber = num; // Update minNumber if a smaller number is found
        }
    }
    return minNumber; // Return the smallest number
}

// Test the function
const numbers = [5, 2, 9, 1, 5, 6];
console.log(`The array is: [${numbers}]`);
console.log(`The minimum number is: ${findMin(numbers)}`);

Output:

The array is: [5, 2, 9, 1, 5, 6]
The minimum number is: 1

4. Step By Step Explanation

1. We initiate by defining our findMin function that receives an array named numbers.

2. Inside this function, a variable minNumber is set with the value of the array's first element. This is our preliminary assumption for the minimum value.

3. Using a for-of loop, each number (num) in the numbers array is accessed. Every number is then compared against the current value of minNumber.

4. If num is found to be smaller than minNumber, the value of minNumber is updated with that of num.

5. As the loop progresses, each number from the array is juxtaposed with our current minimum, adjusting it when required. Therefore, when the loop concludes, minNumber embodies the smallest value within the array.

6. This minimum value is then returned.

7. For verification, we evaluate our function using an exemplar array of numbers, subsequently presenting the array and its smallest element.

Comments