0

I want to make an Array of 100 elements from numbers[1,10] and then count how many of every number is in that Array. How can I do it? I have the Array with random numbers:

function random(min, max) {
   return Math.floor(Math.random() * (max - min + 1)) + min;
}

for(var y=0 ; y<100 ; y++)
{
   tab[y]=random(1, 10);
}

but I don't know how to search for every number.

4
  • sort array uisng var sorted_arr = yourarrayname.sort(); then count it will be easier Commented Mar 9, 2015 at 12:31
  • buddy, @heylala, check out link w3schools.com/jsref/tryit.asp?filename=tryjsref_length_array Commented Mar 9, 2015 at 12:31
  • 1
    buddy, @Victor, should probably read the whole question instead of just the title. Commented Mar 9, 2015 at 12:33
  • 1
    okay, got it @squint! Commented Mar 9, 2015 at 12:34

1 Answer 1

0

You can

function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var tab = [];
for (var y = 0; y < 100; y++) {
    tab[y] = random(1, 10);
}

//counter the instances of each number
var counter = {};
for (var i = 0; i < tab.length; i++) {
    if (!counter[tab[i]]) {
        counter[tab[i]] = 0;
    }
    counter[tab[i]]++;
}

console.log(counter)

Demo: Fiddle

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.