Skip to content Skip to sidebar Skip to footer

Return 0 If There Are No String In An Array - Js

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

Solution 1:

There are probably some more elegant ways to solve this. but this fixes your bug.

function findSmallestNumberAmongMixedElements(arr) {

  var smallestNum = Infinity;
  var numberFound = falsefor(var i = 0; i < arr.length; i++){
     if(typeof arr[i] === 'number' && arr[i] < smallestNum){
         smallestNum = arr[i];
         numberFound = true
     } 
   }
    if(numberFound)
      return smallestNum;

  return0;
}

Solution 2:

functionfindSmallestNumberAmongMixedElements(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 == Infinity? 0 : smallestNum; // if smallest doesn't change return 0
  } 
  return0;
}


var output = findSmallestNumberAmongMixedElements(['sam', 3, 2, 1]);
console.log(output);

Solution 3:

You could use an odd way of using Array#reduce and Array#filter

First, filter out non-numeric

Second reduce this filtered array, with an initial value of 0 - if the array is zero length, reduce will return 0

functionfindSmallestNumberAmongMixedElements(arr) {
    var smallestNum = Infinity;
    return arr.filter(item =>typeof item == 'number').reduce((min,item) => {
        if(item < smallestNum) smallestNum = item;
        return smallestNum;
    }, 0);
}
console.log(findSmallestNumberAmongMixedElements([]));
console.log(findSmallestNumberAmongMixedElements(['1','2','3']));
console.log(findSmallestNumberAmongMixedElements([1,2,3]));
console.log(findSmallestNumberAmongMixedElements(['1',2,3]));

Post a Comment for "Return 0 If There Are No String In An Array - Js"