The issue is that a function can only return once. So when you first iterate over the array and get one then it returns and the function is done running. Math.max()
returns the max from 0 or more numbers, so if you only pass it one number it will always return that same number. Something like below will work.
const obj = {
key: [1, 2, 4]
}
function getLargestElementAtProperty(obj, key) {
let largest;
if (!Array.isArray(obj[key])) {
return undefined
}
for (num in obj[key]) {
if (!largest || largest < obj[key][num]) {
largest = obj[key][num];
}
}
return largest;
}
var output = getLargestElementAtProperty(obj, 'key');
console.log(output); // --> expected 4
Also if you can use Math.max
and the spread operator to achieve the same thing in a more modern JavaScript way like so:
const obj = {
key: [1, 2, 4]
}
function getLargestElementAtProperty(obj, key) {
if (!Array.isArray(obj[key])) {
return undefined
}
return Math.max(...obj[key]);
}
var output = getLargestElementAtProperty(obj, 'key');
console.log(output);
Hope that helps!