1

I have an array of size 50 that holds random integers between 1 and 49.

I would like to be able to count the amount of times the numbers between 10 and 19 occur within the array.

<script type = "text/javascript">
   var arr = [];

   function getRandom( num ){
       return Math.round(Math.random() * num)+1;
   }

   var counter = 0;

   for (var i = 0; i < 50; i++) {
       arr.push(getRandom( 49 ));
       counter++;
   }
1
  • So check if the number is between 10 and 19 before incrementing the counter. What's the problem? Commented Sep 1, 2013 at 15:17

3 Answers 3

1
var count=0;
for (var i=0;i<50;i++{
  if(arr[i]<19 && arr[i]>10){
    count++;
  }
}

that is if you mean 10 and 19 not to be counted if you want to count 10 and 19 also, then change the limit to 20 and 9

Sign up to request clarification or add additional context in comments.

1 Comment

Or change the comparisons to <= and >=.
0

Try using the Arry.filter method:

var nBetween10and19 = [yourArraY]
                       .filter(function(b){return b>10 && b<19;}).length;

See MDN for information on Array.filter and a shim for older browsers

Comments

0

It is always a good idea to make a function because you can reuse it later with different parameters.

I wrote a function that accepts min and max values, and counts the number of occurrences that satifies the limits.

you can pass null for either min or max if you do not want to specify them.

function countRange(list, min, max) {
    var c = 0;
    for (var i = 0, l = list.length, item; i < l; i++) {
        item = list[i];
        if ((min == null || item >= min) && (max == null || item <= max)) {
            c++;
        }
    }
    return c;
}

countRange(arr, 10, 19); // count x >= 10 and x <= 19
countRange(arr, 10, null); // count x >= 10
countRange(arr, null, 30); // count x <= 30

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.