You can use the for
loop to find the indexes of the highest and lowest numbers in a JavaScript array.
let numbers = [5, 2, 9, 7, 1, 3, 8]
let maxIndex = 0
let minIndex = 0
for (let i = 1; i < numbers.length; i++) {
// Get index of the highest item
if (numbers[i] > numbers[maxIndex]) {
maxIndex = i
}
// Get index of the lowest item
if (numbers[i] < numbers[minIndex]) {
minIndex = i
}
}
console.log(maxIndex) // 2
console.log(minIndex) // 4
Explanation
Here I have an array of numbers. I want to get the indexes of the highest and lowest number of that array.
Let's declare 2 variables to store the index values.
You have to use the for loop to iterate over the array of numbers. Because inside the for loop, it will be easy to find the highest and lowest values.
Get Index of The Highest Number
Inside the for
loop, check if the current element numbers[i]
is greater than the element at the index maxIndex
in the array.
If it is greater, then reassign the maxIndex
variable with the current index (i) value.
Get Index of The Lowest Number
Inside the for
loop, check if the current element numbers[i]
is lower than the element at the index maxIndex
in the array.
If it is lower, then reassign the minIndex variable with the current index (i) value.
After finishing the loop, if you check the maxIndex and minIndex variables, you will get the indexes of the highest and lowest numbers of that array.