DEV Community

Md Yasin Miah
Md Yasin Miah

Posted on

How many way to find max number in array on Javascript.

1. With for-loop

const array = [-29, 5, 0, 3, 111, 99, 2, 99];

function maxNumberInArray(arr) {
    let maxNumber = arr[0];
//same way can apply on other loop like(For In, For Of, While)
    for(let i = 0; i < arr.length; i++){
        if(arr[i] > maxNumber){
            maxNumber = arr[i];
        }
    }
    return maxNumber;
}
console.log(maxNumberInArray(array));
Enter fullscreen mode Exit fullscreen mode

2. With forEach

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

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

console.log(maxNumberInArray(array));
Enter fullscreen mode Exit fullscreen mode

3. Using Math.max function.

let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(Math.max(...array))
Enter fullscreen mode Exit fullscreen mode

4. Using reducer

let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(array.reduce((element,max) => element > max ? element : max, 0));
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
peerreynders profile image
peerreynders

Put differently:

const array = [-1, 10, 30, 45, 5, 6, 89, 17];
// `(previousValue, currentValue, index, array) => nextValue`
// Notice how all data (`currentValue`, `index`, `array`) 
// associated with the array being folded is "bunched up" 
// to the right/end of the parameter list.
const selectMax = (previous, value) => value > previous ? value : previous;
// 1. `initialValue` is optional without it `array[0]` 
//    becomes the `initialValue` and processing starts 
//    at `array[1]`
// 2. Without `initialValue` an empty array will cause:
//    `TypeError: Reduce of empty array with no initial value`
//    So empty arrays have to be handled separately
const maxValue = array.length > 0 ? array.reduce(selectMax) : undefined;
console.log(maxValue);
Enter fullscreen mode Exit fullscreen mode

Technically using Number.NEGATIVE_INFINITY would be logically improper if the array had no elements,

While I agree that is exactly what happens with Math.max():

console.log(Math.max()); // -Infinity
Enter fullscreen mode Exit fullscreen mode

Perhaps that is consistent with

console.log(typeof NaN); // "number"
console.log(typeof Number.NEGATIVE_INFINITY); // "number"
Enter fullscreen mode Exit fullscreen mode

i.e. return a value that is "a number" put invalidates most following numeric operations without forcing the script to stop (throw an error).

Collapse
 
lexlohr profile image
Alex Lohr • Edited

With recursion (just for completeness):

const maxInArray = (array, index = 0, max = -Infinity) =>
  index === array.length
  ? max
  : maxInArray(
      array,
      index + 1,
      array[index] > max ? array[index] : max
    )
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jamesdenholm profile image
James Denholm • Edited

Handling negative numbers could be achieved by using Number.NEGATIVE_INFINITY for initialValue (instead of 0), or even just leaving initialValue empty (as reduce() then uses the first element of the array). Technically using Number.NEGATIVE_INFINITY would be logically improper if the array had no elements, but you'd get a TypeError then anyway.

That said, I don't think element and max being around the wrong way is a practical issue; they are by convention (and for code readability should be swapped), but functionally this implementation of callbackFn will still work as the only thing that matters is that the greater of the two args is returned. It's something I'd punt back in a code review, but it'd pass tests, so to speak.

Collapse
 
bwca profile image
Volodymyr Yepishev

I think what's funny is that with javascript's dynamic typing sometimes it is a good idea to ensure the array you are using is in fact an array of numbers, i.e.

let array = [-1, 10, 30, 45, 5, 6, 89, 17, "Bob"];
console.log(array.reduce((element,max) => element > max ? element : max, 0));
Enter fullscreen mode Exit fullscreen mode

would produce "Bob" as the max number, which is hilarious :D

Collapse
 
trangchongcheng profile image
cucheng

Do you think about this way: array.sort()[0]