2

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.

9
  • 3
    Math.max.apply({}, array); Commented Feb 11, 2019 at 3:05
  • Or search the web for "Kth largest element". e.g.: geeksforgeeks.org/kth-smallestlargest-element-unsorted-array This is typically an interview question. Commented Feb 11, 2019 at 3:06
  • There is no need for nested for loops here. Hint: use a variable to store the max value Commented Feb 11, 2019 at 3:07
  • Sure you can put anything in a loop, real question is should you? Commented Feb 11, 2019 at 3:09
  • 1
    @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. Commented Feb 11, 2019 at 3:10

15 Answers 15

12

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for pointing that out lol, I have must have mistyped it. But yeah I have edited it that very instant.
But why use the spread syntax here? What does it do, and how is that related to how Math.max reads numbers?
The spread operator turns the array into a list of parameters, max doesn't take an array as the argument.
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.
Reduce is much more performant jsperf.com/max-vs-reduce/1
5

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);

Comments

4

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;
}

3 Comments

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];.
Who is "zer00ne"? Based on the time of posting, it could refer to any of the answers here (including the deleted one).
@PeterMortensen I have linked it here just in case.
0

The simplest way is using Math.max.apply:

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

function biggestNumberInArray(arr) {
  return Math.max.apply(Math, arr);
}

console.log(biggestNumberInArray(array));

If you really want to use a for loop, you can do it using the technique from this answer:

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

function biggestNumberInArray(arr) {
  var m = -Infinity,
    i = 0,
    n = arr.length;
  for (; i != n; ++i) {
    if (arr[i] > m) {
      m = arr[i];
    }
  }
  return m;
}

console.log(biggestNumberInArray(array));

And you could also use reduce:

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

function biggestNumberInArray(array) {
  return array.reduce((m, c) => c > m ? c : m);
}

console.log(biggestNumberInArray(array));

1 Comment

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.
0

I think you misunderstand how loops are used - there is no need to have three nested loops. You can iterate through the array with a single loop, keeping track of the largest number in a variable, then returning the variable at the end of the loop.

function largest(arr) {
var largest = arr[0]
arr.forEach(function(i) {
  if (i > largest){
    largest = i 
  }
}
return largest;
}

Of course you can do this much more simply: Math.max(...arr) but the question does ask for a for loop implementation.

Comments

0

This is best suited to some functional programming and using a reduce, for loops are out of favour these days.

const max = array => array && array.length ? array.reduce((max, current) => current > max ? current : max) : undefined;

console.log(max([-1, 0, 3, 100, 99, 2, 99]));

This is 70% more performant than Math.max https://jsperf.com/max-vs-reduce/1

Comments

0

Another visual way is to create a variable called something like maxNumber, then check every value in the array, and if it is greater than the maxNumber, then the maxNumber now = that value.

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

function biggestNumberInArray(arr) {
    let maxNumber;
    for(let i = 0; i < arr.length; i++){
        if(!maxNumber){ // protect against an array of values less than 0
            maxNumber = arr[i]
        }
        if(arr[i] > maxNumber){
            maxNumber = arr[i];
        }
    }
    return maxNumber
}
console.log(biggestNumberInArray(array));

I hope this helps :)

Comments

0

var list = [12,34,11,10,34,68,5,6,2,2,90];
var length = list.length-1;
for(var i=0; i<length; i++){
    for(j=0; j<length; j++){
        if(list[j]>list[j+1]){
                [ list[j] , list[j+1] ] = [ list[j+1] , list[j] ];
        }
    }
}
console.log(list[list.length-1]);

1 Comment

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.
0

You Can try My codes to find the highest number form array using for loop.

  
function largestNumber(number){
    let max = number[0];
    for(let i = 0; i < number.length; i++){
        let element = number[i];
        if(element > max){
            max = element;
        }
    }
    return max;
}
let arrayNum= [22,25,40,60,80,100];
let result = largestNumber(arrayNum);
console.log('The Highest Number is: ',result);

Comments

0
let arr = [1,213,31,42,21];
let max = 0;

for(let i = 0; i < arr.length; i++) {
    if(arr[i] > max) {
    max = arr[i]
  } 
}

console.log(max)

1 Comment

If all elements are negative, this will not work.
0

There are multiple ways.

way - 1 | without for loop

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

// way - 1 | without for loop
const maxValue = Math.max(...data);
const maxIndex = data.indexOf(maxValue);
console.log({ maxValue, maxIndex }); // { maxValue: 100, maxIndex: 3 }

way - 2 | with for loop

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

// way - 2 | with for loop
let max = data[0];
for (let i = 0; i < data.length; i++) {
    if (data[i] > max) {
        max = data[i];
    }
}
console.log(max); // 100

Comments

0

THis is the simple function to find the biggest number in array with for loop.

// Input sample data to the function
var arr = [-1, 0, 3, 100, 99, 2, 99];

// Just to show the result
console.log(findMax(arr));

// Function to find the biggest integer in array
function findMax(arr) {
  // size of array
  let arraySize = arr.length;
  if (arraySize > 0) {
    // Initialize variable with first index of array
    var MaxNumber = arr[0];
    for (var i = 0; i <= arraySize; i++) {
      // if new number is greater than previous number
      if (arr[i] > MaxNumber) {
        // then assign greater number to variable
        MaxNumber = arr[i];
      }
    }
    // return biggest number
    return MaxNumber;
  } else {
    return 0;
  }
}

Comments

0

You can try this if you want to practice functions

const numbs = [1, 2, 4, 5, 6, 7, 8, 34]; 

let max = (arr) => {
  let max = arr[0];

  for (let i of arr) {
    if (i > max) {
      max = i;
    }
  }
  return max;
};

let highestNumb = max(numbs);
console.log(highestNumb);

Comments

-1

const array = [-1, 0, 3, 100, 99, 2, 99] let longest = Math.max(...array);

4 Comments

These are not loops. And, again, this adds nothing to the set of existing answers.
We want to find a big number. This approach is wrong?
“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.
And please don’t repeat other answers . means ?
-1

what about this

const array = [1, 32, 3, 44, 5, 6]
console.time("method-test")
var largestNum = array[0]
for(var i = 1; i < array.length; i++) {
  largestNum = largestNum > array[i] ? largestNum : array[i]  
}
console.log(largestNum)
console.timeEnd("method-test")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.