Finding the Minimum Value in a JavaScript Array
This challenge focuses on a fundamental programming task: identifying the smallest element within a given array of numbers. Efficiently finding the minimum value is a common operation in various algorithms and data processing scenarios, such as sorting, data analysis, and optimization problems. Your task is to write a JavaScript function that accurately determines the minimum value in an array.
Problem Description
You are required to write a JavaScript function named findMinimum that takes a single argument: an array of numbers. The function should iterate through the array and return the smallest number present within it.
Key Requirements:
- The function must handle arrays containing positive, negative, and zero values.
- The function should return the actual minimum value, not its index.
- The function should work correctly even if the array contains duplicate values.
- The function should handle edge cases, such as an empty array.
Expected Behavior:
The function should return the minimum value found in the array. If the array is empty, the function should return undefined.
Edge Cases to Consider:
- Empty Array: What should the function return if the input array is empty?
- Array with One Element: What should the function return if the array contains only one element?
- Array with Duplicate Minimum Values: Does it matter which duplicate minimum value is returned?
- Array with all negative numbers: Ensure the function correctly identifies the largest negative number (closest to zero) as the minimum.
Examples
Example 1:
Input: [3, 1, 4, 1, 5, 9, 2, 6]
Output: 1
Explanation: The smallest number in the array is 1.
Example 2:
Input: [-5, -2, -8, -1, -9]
Output: -9
Explanation: The smallest number (largest negative number) in the array is -9.
Example 3:
Input: [0, 0, 0, 0]
Output: 0
Explanation: All elements are the same, so the minimum is 0.
Example 4:
Input: []
Output: undefined
Explanation: The array is empty, so there is no minimum value.
Constraints
- The input array will contain only numbers (integers or floating-point numbers).
- The array can contain between 0 and 100,000 elements.
- The function should have a time complexity of O(n), where n is the number of elements in the array. Avoid nested loops or inefficient operations.
- The function should not modify the original array.
Notes
Consider initializing a variable to store the current minimum value. Iterate through the array, comparing each element to the current minimum. If an element is smaller than the current minimum, update the minimum variable. Remember to handle the edge case of an empty array appropriately.