Skip to content
Sign upLog in
← Back to Community
finding the largest number in an array
Profile icon
DamienVapes

I have some code im having trouble with if someone could give me an idea or an answer id be greatly in your debt.

function getLargestNumber(numbers) {

}

/* Do not modify code below this line */

const largestNumber = getLargestNumber([1, 9, 5]);
console.log(largestNumber, '<-- should be 9');

Answered by LeonDoesCode [earned 5 cycles]
View Answer
Voters
Profile icon
zed123four
Profile icon
PhuThaiThai
Profile icon
DamienVapes
Comments
hotnewtop
Profile icon
LeonDoesCode

In JavaScript, you can use the Math.max.apply() function to do this, like so:

// Will return the largest number function getLargestNumber(numbers) { // Takes in Math and the array of numbers, and returns the largest one return Math.max.apply(Math, numbers); } // Or function getLargestNumber(numbers) { return Math.max(...numbers); }

This is like calling:

function getLargestNumber() { // This function returns the largest number from all the numbers parsed in return Math.max(5, 7, 3, 2); }

You can also do this with Math.min too.

Hope this is what you were looking for!

Profile icon
theangryepicbanana

@LeonDoesCode
In the future, please do not give direct answers. Instead, try to help them understand how to do it

Profile icon
LeonDoesCode

@theangryepicbanana
That is why I also included the second part (after "This is like calling:"). It explains what that function is similar to calling, and how that function works.

However, I see your point, will try to not do this in future. Thanks for the feedback!

Profile icon
DamienVapes

@LeonDoesCode
thank you i was over complicating this..i was trying to put in a for loop and everything lol

Profile icon
LeonDoesCode

@DamienVapes
Gald it helped!

Profile icon
DamienVapes

@LeonDoesCode
how did you post the code the way you did on your earlier comment.id like to show my repl completed here

Profile icon
LeonDoesCode

@DamienVapes
You can post code like so:

Use these at the beginning and end ``` You can also put a language name on the first one e.g ```python

I recommend looking at this for more information.

However, if you want to post a Repl, it is recommended that you use the share Repl feature when you post the code (above the title).