JavaScript Part 1: 22-Exercise 6- Get Max

I have two questions about this exercise. It is an exercise about finding the largest number in the array.

First question:
I wrote

const numbers = [1,2,3,4,100];
const max = getMax(numbers);
console.log(max);

function getMax(array){
    if (array.length === 0) return undefined;

    return Math.max(...array);
}

and it works. Just want to know is there anything wrong or anything that I should consider with my solution?
Here is Mosh’s answer:

function getMax(array){
    if (array.length === 0) return undefined;

    let max = array[0];
    for (let i = 1; i < array.length; i++)
    if (array[i] > max)
        max = array[i];

    return max;
}

Second question:
In the middle of the video when Mosh is writing the code using the reduce method, he wrote:

function getMax(array){
    if (array.length === 0) return undefined;

    array.reduce((accumulator, current) =>{
        if (current > accumulator) return current;
        return accumulator;
    });
}

this doesn’t work, and

function getMax(array){
    if (array.length === 0) return undefined;

    array.reduce((accumulator, current) =>{
        return (current > accumulator)?current : accumulator;
    });
}

this doesn’t work too.

The code only works until he simplified it into this.

function getMax(array){
    if (array.length === 0) return undefined;

   return array.reduce((a,b) => (a,b) ? a:b;
}

Can anyone explain why the two didn’t work and only the last one works? Am I missing something here?

Second question solved. I forgot to put return keyword in front of array.reduce.

Nothing wrong, I think Mosh was just trying to show you how to actually do it yourself rather than relying on an existing function (ie. Math.max) to do it for you. Frankly, if existing common tooling can do it for you, there is never a need to write it yourself. Knowing how to write it yourself is still potentially useful (at least pedagogically).


And I am happy you were able to resolve the second part on your own.

:duck:

Hi, I am having issues with this code execution;

et productdisplay = new Surfexcel(33, ‘a’);
let productdisplay1 = new Surfexcel(33, ‘a’);
console.log(areEqual(productdisplay));
console.log(areSame(productdisplay1));

function Surfexcel(age, name) {

this.age = 30;
this.name = 'ayub';

}

function areEqual(productdisplay, productdisplay1) {
return productdisplay1.age === productdisplay.age && productdisplay1.name === productdisplay.name;
}

function areSame(productdisplay, productdisplay1) {

return productdisplay1 === productdisplay;

}

Looks like you forgot to call areEqual and areSame with both parameters:

console.log(areEqual(productdisplay, productdisplay1));
console.log(areSame(productdisplay, productdisplay1));

And please create a new post for distinct questions like this. Thanks!

2 Likes