When we work with an array of numbers, sometimes we need to find out what’s the maximum value, and then find its position in the array.
To do so, you need to use the
Math.max() method combined with the
Let me show you an easy example. Suppose you have an example array as shown below:
const myArray = [7, 35, 17, 64, 23, 91, 51, 22];
To find the greatest number in the array, we can call the
Math.max() method and pass the array as an argument to it.
When passing the array, use the spread operator
... so that each number in the array gets passed as an argument:
const myArray = [7, 35, 17, 64, 23, 91, 51, 22]; const maxValue = Math.max(...myArray); console.log(maxValue); // 91
Now that we have the max value of the array, the next step is to call the
indexOf() method from the array.
maxValue variable as an argument to the
indexOf() method as shown below:
const myArray = [7, 35, 17, 64, 23, 91, 51, 22]; const maxValue = Math.max(...myArray); const maxIndex = myArray.indexOf(maxValue); console.log(maxIndex); // 5
Now we get that the index of the max value, which is 91, is 5. What you want to do with the data next is up to you.
Now you’ve learned how to get the max value of an array using