Categories
JavaScript Answers

How to return index of greatest value in an array with JavaScript?

Spread the love

Sometimes, we want to return index of greatest value in an array with JavaScript.

In this article, we’ll look at how to return index of greatest value in an array with JavaScript.

How to return index of greatest value in an array with JavaScript?

To return index of greatest value in an array with JavaScript, we can use the Math.max method and the array indexOf method.

For instance, we write

const i = arr.indexOf(Math.max(...arr));

to call Math.max with the arguments of arr spread as the arguments of max.

Then we call indexOf on the max number in arr returned by Math.max to get the index of the greatest number in arr.

Conclusion

To return index of greatest value in an array with JavaScript, we can use the Math.max method and the array indexOf method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *