Why is filter returning an array of all numbers instead of a max number. Can someone please check

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

make it so that if the argument given to maxNum is the max value it returns true, and if it’s not it returns false.

Or use a different function, maybe…

Could you please elaborate on how do I do proceed with the first approach. I’m new to JS so I’m finding it difficult to grasp the concepts.

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

Oh got it .Thanks for the clarification ilenia .

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.