Reputation: 113
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]);
Upvotes: 8
Views: 122
Reputation: 318232
The first time the loop runs, smallest
is the first item in the array, as that's how you declare it
var smallest = array[0];
So on the first iteration, smallest
is already 5
, and so is array[i]
, as it's currently also array[0]
, that's where the loop starts, so they are the same, meaning your condition is true on the first iteration, and the count increases.
You're really going about this the wrong way.
The easiest would be to use Math.min
to find the smallest number in the array, and then just filter the array based on that, and see how many indices are left
function small(arr) {
let min = Math.min.apply(null, arr);
return arr.filter(val => val === min).length;
}
console.log(small([5, 6, 2, 2, 2]));
Upvotes: 1
Reputation: 189
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]));
Upvotes: 4
Reputation: 9808
you can use two loops here and first get the smallest number and then count the number of times it occurs. Time complexity will still be O(n).
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];
}
}
for(var i=0; i<array.length; i++){
if(smallest===array[i]) {
count++;
}
}
return count;
}
console.log( small([5,6,2,2,2]));
Upvotes: 2
Reputation: 1290
You should set count
to 0 if you replace smallest
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;
}
small([5,6,2,2,2]);
Upvotes: 0
Reputation: 504
You set smallest to
array[0]
and if statement says
smallest = array[i]
it is always true. You need to set smallest = 0 or smallest = 1.
Upvotes: 0