Using a for loop to find the biggest number in an array

Viewed 38

I've asked this question before but I forgot a key detail. I have to use a for-loop to figure to find the answer. I dont understand why my code is not working, when I read it logically I feel that it should work, but what it does is return 3,4,2 as opposed to the highest number of the 3 (i.e. 4)

const array2 = ['a', 3, 4, 2] // should return 4

for(items of array2){
    if(items > 0) {
        console.log(Math.max(items));
}

What am I doing wrong? What have I misinterpreted? Please dont just give me the answer, explain why your way works and mine does not! Thank you

4 Answers

let arr = ["a", 3, 5, 8, 100, 20];

let max = Math.max(...arr.filter(e => typeof e !== "string"));

console.log(max);

OR

let arr = ["a", 3, 5, 8, 100, 20];

let max;

for (item of arr) {
  if (typeof item != "string") {
    if (max) {
      if (max < item) max = item;
    } else {
      max = item;
    }
  }
}


console.log(max);

If you NEED to use a loop, then u shouldn't use Math.max() as it takes an undefined list of parameters (not an array, and no other types than numbers). You can still manage to filter the array beforehand or check the type.

The error you do is that you use the function Math.max() in a loop that already "works as a loop"

Here is the spec :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

A simple way to do a loop is :

max = 0
for(item in array2){
    if(item>max){
        max=item
    }
}
console.log(max)

edit: you can check with typeof to avoid errors and initiate the value of max with -Infinity or else you can't get the max out of negative numbers

    const array2 = ['a', 3, 4, 2] // should return 4
    let max = -Infinity
    for(items of array2){
        if (typeof items == "string") continue;
        if(items > max) {
            max = items
    }}
    console.log(max)

Your method isn't working because in your for loops, items is each element of the array. So calling Math.max on 3 will return 3 and on 4 will return 4

Your issue: the Math.max needs more than 1 parameter!

The bad solution: filter to get only number, the spread the result array as params of Math.max. 3 times O(N).

Simple solution: write your own findMax function:

const findMax = (arr) => {
    let max = -Infinity;
    for(let i of arr){
        if(typeof(i) === 'number' && i > max)
            max = i
    }
    return max;
}

findMax(['a', 3, 4, 2])
Related