Start with a simple running minimum. Then track the index when you also need the position.
Example 1 — Linear Scan
Keep a running minimum and update it whenever a smaller element appears.
JavaScript
function findMin(arr) {
if (!arr || arr.length === 0) {
throw new Error("Array must not be empty.");
}
let min = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
const numbers = [12, 45, 2, 42, 19];
console.log("Minimum = " + findMin(numbers));
Reject empty (or missing) arrays before reading arr[0].
Seed min with the first element.
Loop from index 1 so you never compare the seed against itself needlessly.
Update when arr[i] < min.
Return the final running minimum after one pass.
Example 2 — Track Index
Same scan, but also remember the first index where the minimum appears.
JavaScript
function findMinIndex(arr) {
if (!arr || arr.length === 0) {
throw new Error("Array must not be empty.");
}
let minIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
const numbers = [12, 45, 2, 42, 19];
const index = findMinIndex(numbers);
console.log("Min = " + numbers[index] + " at index " + index);