I’m new to JavaScript and need some help! I created an array containing several numerical values and wrote a function to determine the smallest value. However, I’m curious if it’s possible to also retrieve the index of that smallest number, even if I modify the array later on. Below is my current code for reference:
function findMinIndex() {
let minIndex = -1;
const values = [29, 26, 44, 80, 12, 15, 40];
let minValue = Infinity;
for (let j = 0; j < values.length; j++) {
if (values[j] < minValue) {
minValue = values[j];
minIndex = j;
}
}
console.log(minIndex);
}
findMinIndex();
If you’re looking for something a bit different, you could try using a combination of Array.prototype.forEach. This method allows you to iterate over the array while keeping track of the current minimum value and its index manually. It’s quite readable and easy to understand, especially if you’re still getting used to JavaScript array methods.
function findMinIndex(arr) {
let minIndex = 0;
let minValue = arr[0];
arr.forEach((value, index) => {
if (value < minValue) {
minValue = value;
minIndex = index;
}
});
return minIndex;
}
let myArray = [29, 26, 44, 80, 12, 15, 40];
console.log(findMinIndex(myArray));
I find forEach makes it easier to reason about the logic if you’re not modifying the array while iterating. Give this a shot and see how it feels to you!
Hey, a useful tip for finding both the minimum value and its index is to use the reduce method, which can make your code more concise and clear. With reduce, you can simultaneously track the smallest value and its index in just one go through the array. Here’s a simple way to do it:
This approach essentially keeps updating the index of the smallest value found so far as it iterates through the array. It’s efficient and pretty straightforward once you’re comfortable with reduce. Give it a try!