How can I find the maximum or minimum value in an array in JavaScript?
Antek N
antek n profile pic

To find the maximum or minimum value in an array in JavaScript, you can use various methods such as a loop, theMath.max() andMath.min() functions, or the spread operator. Here's a step-by-step guide on how to achieve this: 1. Define the array:

1
2
3

   const array = [5, 2, 8, 1, 9, 4];
   

Replace[5, 2, 8, 1, 9, 4] with your own array of numbers. 2. Using a loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

   let max = array[0];
   let min = array[0];

   for (let i = 1; i < array.length; i++) {
     if (array[i] > max) {
       max = array[i];
     }
     if (array[i] < min) {
       min = array[i];
     }
   }

   console.log('Maximum:', max);
   console.log('Minimum:', min);
   

This loop iterates through the array and updates themax andmin variables accordingly. 3. UsingMath.max() andMath.min():

1
2
3
4
5
6
7

   const max = Math.max(...array);
   const min = Math.min(...array);

   console.log('Maximum:', max);
   console.log('Minimum:', min);
   

The spread operator (...) spreads the array elements as arguments to theMath.max() andMath.min() functions, which return the maximum and minimum values, respectively. 4. Using thereduce() method:

1
2
3
4
5
6
7

   const max = array.reduce((a, b) => Math.max(a, b));
   const min = array.reduce((a, b) => Math.min(a, b));

   console.log('Maximum:', max);
   console.log('Minimum:', min);
   

Thereduce() method applies a reducer function to each element of the array, comparing and returning the maximum or minimum value. Choose the method that best suits your needs and adjust the code as necessary to fit your specific use case and handle different types of values within the array.