I have a function here that takes the smallest number in an array.
What I did is that I filtered out only numbers using typeof property and compared the values from Infinity.
Right now, it will return 0 if the array is empty.
However if the array contains only string or other datatypes it will return Infinity.
Here's my codes:
function findSmallestNumberAmongMixedElements(arr) {
var smallestNum = Infinity;
if(arr.length !== 0){
for(var i = 0; i < arr.length; i++){
if(typeof arr[i] === 'number' && arr[i] < smallestNum){
smallestNum = arr[i];
}
}
return smallestNum;
}
return 0;
}
var output = findSmallestNumberAmongMixedElements(['sam', 3, 2, 1]);
console.log(output); // --> 4
It must return 0 as well if there are no numbers in the array.
Any idea what am I doing wrong here?
smallestNumto0instead ofInfinity.findSmallestNumberAmongMixedElements(['sam', 3, 2, 1])is returning1for me. Can you provide other test cases?return smallestNum;toreturn (smallestNum < Infinity) ? smallestNum : 0;