简体   繁体   中英

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]); 

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])); 

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])); 

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])); 

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]);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM