How Get the bigger number inside a array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How Get the bigger number inside a array

I want know how I can show the bigger number of a array between several number in the array For example if I make this how I can print the bigger number? Num1=prompt("first number"); Num2=prompt("second number"); Num3=prompt("three number"); Resul=[Num1,Num2,Num3]

3rd Nov 2020, 7:54 AM
Joan Manuel
Joan Manuel - avatar
4 Answers
+ 4
Use max method form Math class=> Math.max(...Resul)
3rd Nov 2020, 8:04 AM
Abhay
Abhay - avatar
+ 4
(if you don't know about three dots, heres the explanation) Math.max() takes as many arguments as you need, but you don't pass the array directly, you should spread it. Wrong: Math.max([1,2,3]) Right: Math.max(1,2,3) That is why you use three dots to spread the array into their own elements, Math.max(...Resul)
3rd Nov 2020, 9:17 AM
maf
maf - avatar
+ 3
let maxNum = Math.max(...array) // just find the index of the maximum number in that array using findIndex. let maxIndex = array.findIndex(num => num === maxNum) If you wanna do it the whole process manually: let maxAns = { value: null, index: null } /* making an answer object that contains index and value of the highest number, initially null. */ array.forEach((num, index) => { /* Checking if the number in the loop is greater than maxAns.value, or if maxAns.value is null, if it is true, set the current num and index in maxAns */ if(num > maxAns.value || maxAns.value === null) { maxAns.value = num maxAns.index = index } }) /* Looping through array, you can also use the for(let i = 0....) loop */ console.log(maxAns) If u didnt understand any line, ask.
3rd Nov 2020, 9:59 AM
maf
maf - avatar
+ 2
maf in how I show the max number with their position in the array (if the max numbers is 50 in his position inside the array for example is 5
3rd Nov 2020, 9:31 AM
Joan Manuel
Joan Manuel - avatar