Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the same value number in array

I'm working on a challenge where I have to find the smallest value in an array and be able to count it if the number occurs more than once. I think I have the format down, but it gives me one more count than there are numbers(4 instead of 3). Can anyone give me some tips? Appreciate any help!

function small(array) {
  var smallest = array[0];
  var count = 0;
  for(var i = 0; i < array.length; i++) {
    if(array[i] < smallest) {
      smallest = array[i];
    }
    if(smallest===array[i]) {
      count++;
    }
  }
  return count;
}

small([5,6,2,2,2]);
like image 405
grasshopper Avatar asked Jul 21 '17 22:07

grasshopper


1 Answers

whenever you will get new smallest, then reset is required.

Why its needed to reset count to 0 not 1 ?

because condition is checking with smallest === arr[i], means you are checking same element which you have stored now

function small(array){
    var smallest = array[0];
    var count = 0;
    for(var i = 0; i < array.length; i++) {
        if(array[i] < smallest) {
            smallest = array[i];
            count = 0;
        }
        if(smallest===array[i]) {
            count++;
        }
    }
    return count;
 }
 console.log(small([5,6,2,2,2]));
like image 176
Kaps Avatar answered Nov 15 '22 15:11

Kaps