Find the biggest number in an array by using JavaScript loops

22,303

Solution 1

zer00ne's answer should be better for simplicity, but if you still want to follow the for-loop way, here it is:

function biggestNumberInArray (arr) {
    // The largest number at first should be the first element or null for empty array
    var largest = arr[0] || null;

    // Current number, handled by the loop
    var number = null;
    for (var i = 0; i < arr.length; i++) {
        // Update current number
        number = arr[i];

        // Compares stored largest number with current number, stores the largest one
        largest = Math.max(largest, number);
    }

    return largest;
}

Solution 2

Some ES6 magic for you, using the spread syntax:

function biggestNumberInArray(arr) {
  const max = Math.max(...arr);
  return max;
}

Actually, a few people have answered this question in a more detailed fashion than I do, but I would like you to read this if you are curious about the performance between the various ways of getting the largest number in an array.

Solution 3

There are multiple ways.

  1. Using Math max function

let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(Math.max(...array))
  1. Using reduce

let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(array.reduce((element,max) => element > max ? element : max, 0));
  1. Implement our own function

let array = [-1, 10, 30, 45, 5, 6, 89, 17];

function getMaxOutOfAnArray(array) {
  let maxNumber = -Infinity;
  array.forEach(number => { maxNumber =  number > maxNumber ? number :  maxNumber; })
  console.log(maxNumber);
}

getMaxOutOfAnArray(array);
Share:
22,303

Related videos on Youtube

Jacky
Author by

Jacky

Updated on April 06, 2022

Comments

  • Jacky
    Jacky about 2 years

    Create a function called biggestNumberInArray().

    That takes an array as a parameter and returns the biggest number.

    Here is an array

    const array = [-1, 0, 3, 100, 99, 2, 99]
    

    What I try in my JavaScript code:

     function biggestNumberInArray(arr) {
       for (let i = 0; i < array.length; i++) {
          for(let j=1;j<array.length;j++){
              for(let k =2;k<array.length;k++){
                  if(array[i]>array[j] && array[i]>array[k]){
                        console.log(array[i]);
               }
             }
          }
       }
    }
    

    It returns 3 100 99.

    I want to return just 100 because it is the biggest number.

    Is there a better way to use loops to get the biggest value?

    Using three different JavaScript loops to achieve this (for, forEach, for of, for in).

    You can use three of them to accomplish it.

    • zer00ne
      zer00ne about 5 years
      Math.max.apply({}, array);
    • Wyck
      Wyck about 5 years
      Or search the web for "Kth largest element". e.g.: geeksforgeeks.org/kth-smallestlargest-element-unsorted-array This is typically an interview question.
    • cegfault
      cegfault about 5 years
      There is no need for nested for loops here. Hint: use a variable to store the max value
    • zer00ne
      zer00ne about 5 years
      Sure you can put anything in a loop, real question is should you?
    • Wyck
      Wyck about 5 years
      @cegfault, this is typically the precursor question to getting an interview candidate to implement a kth largest element algorithm or to talk about order statistics. So using max only helps you with the first part. The next part is always how would you find the 2nd largest, or top-2. Then 3, then k.
    • cegfault
      cegfault about 5 years
      ... to getting an interview candidate .... ah. got it
    • Jacky
      Jacky about 5 years
      Ok,I'll try to put Math.max.apply in loops
    • holydragon
      holydragon about 5 years
      You also can sort the array and then pop it.
    • Jacky
      Jacky about 5 years
      Ok,I found the answer...sorry,guys.Can i delete this question?
  • wentjun
    wentjun about 5 years
    Thanks for pointing that out lol, I have must have mistyped it. But yeah I have edited it that very instant.
  • Andy
    Andy about 5 years
    But why use the spread syntax here? What does it do, and how is that related to how Math.max reads numbers?
  • Andy
    Andy about 5 years
    What does apply do, and how does it relate to how Math.max works? The OP probably doesn't know so you should include that information in your answer.
  • Adrian Brand
    Adrian Brand about 5 years
    The spread operator turns the array into a list of parameters, max doesn't take an array as the argument.
  • wentjun
    wentjun about 5 years
    Honestly I dont mean to overcomplicate things! I suggested using the spread syntax because no one else at that point of time has suggested using it.
  • Adrian Brand
    Adrian Brand about 5 years
    Reduce is much more performant jsperf.com/max-vs-reduce/1
  • RobG
    RobG about 5 years
    var a = [1,3,2]; for (var max=a[0], i=1, iLen=a.length; i<iLen; i++) if (a[i]>max) max=a[i];.
  • Peter Mortensen
    Peter Mortensen almost 4 years
    Who is "zer00ne"? Based on the time of posting, it could refer to any of the answers here (including the deleted one).
  • Matheus Pratta
    Matheus Pratta almost 4 years
    @PeterMortensen I have linked it here just in case.
  • Sebastian Simon
    Sebastian Simon over 3 years
    These are not loops. And, again, this adds nothing to the set of existing answers.
  • Trilok Singh
    Trilok Singh over 3 years
    We want to find a big number. This approach is wrong?
  • Sebastian Simon
    Sebastian Simon over 3 years
    “This approach is wrong?” — It’s not the approach demanded in the question, so yes this approach is wrong in this context. When answering, please make sure to answer the question, not just the question title. And please don’t repeat other answers. At least format your code.
  • Trilok Singh
    Trilok Singh over 3 years
    And please don’t repeat other answers . means ?
  • Admin
    Admin over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
  • General Grievance
    General Grievance about 2 years
    If all elements are negative, this will not work.