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?
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.
et productdisplay = new Surfexcel(33, ‘a’);
let productdisplay1 = new Surfexcel(33, ‘a’);
console.log(areEqual(productdisplay));
console.log(areSame(productdisplay1));