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]);
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With