DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on • Edited on

1 1 1 1 1

Find the maximum number in an array - JavaScript

Find the maximum number from an array of positive integers using JavaScript

Solution

//findMaxNumber.js

// 1st Method
function findMaxNumber(numbers) {
//Initializes result to track the maximum number, starting at 0.
  let result = 0;

  //Stores the length of the numbers array for use in the loop.
  const numbersLength = numbers.length;

  //Check if the array is not empty before processing it.
  if (numbersLength > 0) {

    //Loops through each number in the array.
    for (let i = 0; i < numbersLength; i++) {

      //Compare each number to the result to check if it's larger.
      if (numbers[i] > result) {

        //Updates result with the current number if it's the largest
        result = numbers[i];
      }
    }
    console.log(result);
    return result;
  }

  return result;
}

// 2nd Method
function findMaxNumber(numbers) {
  const maxNumber = Math.max(numbers);
  return maxNumber;
}

findMaxNumber([5, 33, 47, 103]);
Enter fullscreen mode Exit fullscreen mode

Result

> 103
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
aaronre16397861 profile image
Aaron Reese

Or use array.sort().slice(-1)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs