How to Find the Index of the Maximum Element in JavaScript?

Estimated read time 1 min read

You can find the index of the maximum element in a JavaScript array by using the reduce method. The reduce method can be used to iterate through an array and compute a single value based on the elements of the array.

Here’s an example:

const array = [1, 3, 5, 7, 2, 4, 6, 8];

const maxIndex = array.reduce((maxIndex, currentValue, currentIndex) =>
  array[maxIndex] < currentValue ? currentIndex : maxIndex, 0
);

console.log(maxIndex); // Output: 3

In this example, the reduce method is used to iterate through the array and compare each value to the current maximum value. The maxIndex is updated with the index of the current maximum value. The reduce method takes three arguments: maxIndex, currentValue, and currentIndex. The maxIndex argument is the accumulated value, which is updated in each iteration of the loop. The currentValue argument is the current element in the array, and the currentIndex argument is the index of the current element. The initial value of maxIndex is set to 0, which is the index of the first element in the array.

The reduce method returns the final value of maxIndex, which is the index of the maximum element in the array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply