Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding min and max in array Javascript

So I try to find the minimum and maximum if an array and want to call the function. I made this code, but it doesn´t work. I just don´t get why.

function getMinMax(arr){
  let maximum = Math.max(arr);
  let minimum = Math.min(arr);
 let result =  ([maximum, minimum]); 
  return result;
};

getMinMax([10,3,8,1,33])
like image 289
thomalex Avatar asked Oct 31 '25 11:10

thomalex


2 Answers

You try to pass array, but functions (min, max) accept only number arguments.

You need to unpack array to array of arguments with the spread operator (...):

const arr = [10, 3, 8, 1, 33];
const min = Math.min(...arr);
const max = Math.max(...arr);

So, your code should be like this:

function getMinMax(arr){
  let maximum = Math.max(...arr);
  let minimum = Math.min(...arr);
 let result =  ([maximum, minimum]); 
  return result;
};

getMinMax([10,3,8,1,33])
like image 55
Sviatoslav Miller Avatar answered Nov 03 '25 04:11

Sviatoslav Miller


You can find the maximum and minimum in 2 ways. First way You go on with maximum and minimum form Math function in javascript, if you need to be used when you have to set numbers from max and min, like this :

let maximum = Math.max(10, 3, 8, 1, 33);
let minimum = Math.min(10, 3, 8, 1, 33);

Now you have an array so you have to convert to As above, for example : let array = [1,2,3,4,5] when you use ... before array you convert array to this : 1,2,3,4,5 for example :

function getMinMaxWithMath(arr){
  // Math.max(10,3,8,1,33)
  let maximum = Math.max(...arr);
  // Math.min(10,3,8,1,33)
  let minimum = Math.min(...arr);
 let result =  ([maximum, minimum]); 
  return result;
};

console.log('getMinMaxWithMath ', getMinMaxWithMath([10,3,8,1,33]));

The second way you can use for loop for example :

function getMinMaxForLoop(arr){
  let maximum = arr[0];
  let minimum = arr[0];
  for (let i = 0 ; i < arr.length; i++) {
    if (maximum < arr[i]) {
      maximum = arr[i];
    } else {
      minimum = arr[i];
    }
    
  }
 let result =  ([maximum, minimum]); 
  return result;
};
console.log('getMinMaxForLoop : ',getMinMaxForLoop([10,3,8,1,33]))

You can Look output from this link;

like image 39
nima amr Avatar answered Nov 03 '25 03:11

nima amr