Ideally it should return only [5] instead it is returning [1,2,3,4,5].
const nums = [1,2,3,4,5];
function maxNum(){
let max = nums[0];
for(let element of nums){
if(max<element){
max = element;
}
}
return max;
}
console.log("Max number is "+nums.filter(maxNum));
filter method calls the callback function with items of the array, one-by-one. If the result of callback function, with item as argument, is truthy item will be included in resulting array, if the result is falsy item will not be included.
So every time max is updated the filter returns the value right?. Can you suggest any modifications to my code that would result in returning max value using filter method
It’s how filter works, it checks each element with the callback and if the callback returns true it keeps the element, if it returns false it discards it. If you want to find the max number, this is not a job for filter, as it returns a new array