Get the Index of the Max Value of an Array in JavaScript
Table of Contents
When you are working with arrays, especially arrays of numbers, you sometimes want to know where the highest value is.
To do this, you'll have to first find the highest value in the array, then find the index of that value.
In this post, we'll learn how to get the index of the highest value of an array in JavaScript.
How to get the index of the highest value of an array
To begin, let's start off with our example array of random numbers from 1 to 100:
JAVASCRIPTconst array = [4, 25, 37, 54, 73, 83, 21, 42];
To get the index of the highest value of an array, we first must find the highest value in the array.
We can do this by using the Math.max
function and pass it the deconstructed array:
JAVASCRIPTconst array = [4, 25, 37, 54, 73, 83, 21, 42];
const highestValue = Math.max(...array);
console.log(highestValue);
BASH83
Now that we have the highest value in the array, we just need to find the index of that value.
We can do this by using the built-in Array.indexOf()
function and passing it the highest value:
JAVASCRIPTconst array = [4, 25, 37, 54, 73, 83, 21, 42];
const highestValue = Math.max(...array);
const highestValueIndex = array.indexOf(highestValue);
console.log(highestValueIndex);
BASH5
Conclusion
In this post, we learned how to get the index of the highest value of an array.
Simply use the Math.max()
function to get the highest value, then use the Array.indexOf()
function to get the index.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications