Ask coding questions

← Back to all posts
Running loop to get max number in array
CarlyRaeJepsenS (1)

What's up guys, I'm trying to find the greatest number in an array with a loop. Although I could easily just use a function, I want to use a loop (for the sake of learning). What am I doing wrong?

Answered by ash15khng (685) [earned 5 cycles]
View Answer
ash15khng (685)

You could have a greatest variable, then for each item in the list check if the item is greater than greatest, and if it is replace greatest with the item.

greatest = 0;
arr3.forEach(function(element) {
    if (element > greatest) {
        greatest = element;
CarlyRaeJepsenS (1)

@ash15khng Thanks man! That'll be a good way for me to use .forEach 👍