index with highest value array in javascript

To get the index of the highest value in an array, you can use the indexOf method in combination with the Math.max method. Here's an example:

index.tsx
const arr = [1, 5, 2, 9, 3]; // Example array
const maxVal = Math.max(...arr); // Get the maximum value
const maxIndex = arr.indexOf(maxVal); // Get the index of the maximum value
console.log(maxIndex); // Output: 3
216 chars
5 lines

In this example, we first create an array with some values. We then use the spread operator to pass the array elements as arguments to the Math.max method, which returns the maximum value. Finally, we use the indexOf method to get the index of the maximum value in the original array.

Note that this method only returns the index of the first occurrence of the maximum value in the array. If there are multiple occurrences of the maximum value, you'll need to modify the code to handle them accordingly.

gistlibby LogSnag