How to get the Index of Max/Min Values in JavaScript Arrays


Dealing with mood swings of Javascript arrays? In this blog post, you will understand how to find the Highs (global maximas) and Lows (global minimas) of JS array. Lets begin.


Getting Max Value(s)

Getting the first index using Math.max() and Array.indexOf()

JavaScript
const heights = [3, 5, 8, 100, 20];
const max = Math.max(...heights);
const index = heights.indexOf(max);

console.log(index); // πŸ‘‰οΈ 3

Explanation:

  • Utilize Math.max(...heights) to find the maximum value.
  • Leverage Array.indexOf() to get the index of the maximum value.
  • ⚠ Note: If multiple peaks share the same maximum value, indexOf returns only the index of the first occurrence.

Getting all the indices using loop and Math.max()

Employ a loop to iterate over the array and push indexes with the maximum value to the indexes array.

JavaScript
const heights = [3, 5, 8, 100, 20, 100];
const max = Math.max(...heights);
const indexes = [];

for (let i = 0; i < heights.length; i++) {
  if (heights[i] === max) {
    indexes.push(i);
  }
}

console.log(indexes); // πŸ‘‰οΈ [3, 5]

Using Array.reduce()

Embrace Array.reduce() to iterate and find the index with the maximum value.

JavaScript
const heights = [3, 5, 8, 100, 20];
const index = heights.reduce((acc, cur, i) => (cur > heights[acc] ? i : acc), 0);

console.log(index); // πŸ‘‰οΈ 3

Or use reduce to accumulate indexes with the maximum value in the indexes array. Now you get all such indices too.

JavaScript
const heights = [3, 5, 8, 100, 20];
const index = heights.reduce((acc, cur, i) => (cur > heights[acc] ? i : acc), 0);

console.log(index); // πŸ‘‰οΈ 3

Getting MinValue(s)

Now that you know Max, almost exact code can be reused for minimas too.

Getting the first index using Math.min() and Array.indexOf()

JavaScript
const depths = [10, 5, 0, 15, 30];
const min = Math.min(...depths);
const index = depths.indexOf(min);

console.log(index); // πŸ‘‰οΈ 2

Explanation:

  • Utilize Math.min(...depths) to find the minimum value.
  • Leverage Array.indexOf() to get the index of the minimum value.
  • ⚠ Note: If multiple peaks share the same maximum value, indexOf returns only the index of the first occurrence.

Getting all the indices using loop and Math.min()

Employ a loop to iterate over the array and push indexes with the minimum value to the indexes array.

JavaScript
const depths = [10, 5, 0, 15, 30, 0, 0];
const min = Math.min(...depths);
const indexes = [];

for (let i = 0; i < depths.length; i++) {
  if (depths[i] === min) {
    indexes.push(i);
  }
}

console.log(indexes); // πŸ‘‰οΈ [2, 5, 6]

Using Array.reduce()

Embrace Array.reduce() to iterate and find the index with the maximum value.

JavaScript
const depths = [10, 5, 0, 15, 30, 0, 0];
const index = heights.reduce((acc, cur, i) => (cur < depths[acc] ? i : acc), 0);

console.log(index); // πŸ‘‰οΈ 2

Or use reduce to accumulate indexes with the minimum value in the indexes array. Now you get all such indices.

JavaScript
const depths = [10, 5, 0, 15, 30, 0, 0];
const min = Math.min(...depths);
const indexes = depths.reduce((acc, cur, i) => (cur === min ? [...acc, i] : acc), []);

console.log(indexes); // πŸ‘‰οΈ [2, 5, 6]

πŸ§ͺPractice Coding Problem: Local Peak Finder πŸ—»

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

You are given an array representing the heights of hills. Your task is to find the index or indices of the peak(s), which are the elements greater than their immediate neighbors. Note, these are not the absolute peaks of the whole array.

JavaScript
/**
 * Find the index or indices of the peak(s) in the given array.
 * @param {number[]} heights - Array representing the heights of hills.
 * @returns {number[]} - Array containing the index or indices of the peak(s).
 */
function findPeaks(heights) {
  // > > > πŸ‘‰ Write code here πŸ‘ˆ < < <  
}

const hillHeights = [1, 3, 2, 5, 1, 4, 2];
console.log(findPeaks(hillHeights)); // πŸ‘‰οΈ [3, 5]
Please attempt before seeing the Answer:
JavaScript
function findPeaks(heights) {
  const peaks = [];

  for (let i = 1; i < heights.length - 1; i++) {
    if (heights[i] > heights[i - 1] && heights[i] > heights[i + 1]) {
      peaks.push(i);
    }
  }

  return peaks;
}

Explanation:

  • The findPeaks function initializes an empty array peaks to store the indices of peaks.
  • It uses a for loop to iterate over each element in the heights array, starting from the second element (index 1) and ending at the second-to-last element.
  • Inside the loop:
    • It checks if the current element is greater than both its immediate neighbors.
    • If the condition is true, the current index i is considered a peak, and it is pushed to the peaks array.
  • The final result is an array (peaks) containing the indices of all the peaks in the input array.

Now you know how scale the heights and dive the depths of a Javascript array.

Keep peaking and keep coding πŸš€!

Scroll to Top