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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jacky
  • 865
  • 2
  • 12
  • 27
  • 3
    `Math.max.apply({}, array);` – zer00ne Feb 11 '19 at 03:05
  • Or search the web for "Kth largest element". e.g.: https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/ This is typically an interview question. – Wyck Feb 11 '19 at 03:06
  • There is no need for nested for loops here. Hint: use a variable to store the max value – cegfault Feb 11 '19 at 03:07
  • Sure you can put anything in a loop, real question is *should you?* – zer00ne Feb 11 '19 at 03: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. – Wyck Feb 11 '19 at 03:10
  • ... *to getting an interview candidate* .... ah. got it – cegfault Feb 11 '19 at 03:11
  • Ok,I'll try to put Math.max.apply in loops – Jacky Feb 11 '19 at 03:11
  • You also can sort the array and then pop it. – holydragon Feb 11 '19 at 03:12
  • Ok,I found the answer...sorry,guys.Can i delete this question? – Jacky Feb 11 '19 at 03:24

15 Answers15

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.

wentjun
  • 40,384
  • 10
  • 95
  • 107
  • Thanks for pointing that out lol, I have must have mistyped it. But yeah I have edited it that very instant. – wentjun Feb 11 '19 at 03:17
  • But _why_ use the spread syntax here? What does it do, and how is that related to how `Math.max` reads numbers? – Andy Feb 11 '19 at 03:20
  • 2
    The spread operator turns the array into a list of parameters, max doesn't take an array as the argument. – Adrian Brand Feb 11 '19 at 03:26
  • 1
    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. – wentjun Feb 11 '19 at 03:39
  • 1
    Reduce is much more performant https://jsperf.com/max-vs-reduce/1 – Adrian Brand Feb 11 '19 at 03:42
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;
}
4

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);
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));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 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. – Andy Feb 11 '19 at 03:23
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

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
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 :)

Spangle
  • 762
  • 1
  • 5
  • 14
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.

jpriebe
  • 824
  • 7
  • 13
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]);
  • 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](/help/how-to-answer). – Community Dec 06 '21 at 14:38
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);
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)
Synchro
  • 1,105
  • 3
  • 14
  • 44
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
Bhavesh Ajani
  • 991
  • 9
  • 11
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;
  }
}
Mr-Faizan
  • 1,179
  • 1
  • 8
  • 9
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);
Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
-1

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

Trilok Singh
  • 1,227
  • 12
  • 10
  • These are not loops. And, [again](https://stackoverflow.com/questions/1669190/find-the-min-max-element-of-an-array-in-javascript/64185694#comment113501714_64185694), this adds nothing to the set of [existing](https://stackoverflow.com/a/54623482/4642212) answers. – Sebastian Simon Oct 03 '20 at 15:23
  • We want to find a big number. This approach is wrong? – Trilok Singh Oct 03 '20 at 15:29
  • _“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](https://meta.stackoverflow.com/q/251361/4642212). – Sebastian Simon Oct 03 '20 at 15:33
  • And please don’t repeat other answers . means ? – Trilok Singh Oct 03 '20 at 15:37
-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")