user3283104
user3283104

Reputation: 416

Pushing unique numbers within a range to an array in Javascript

I am trying to insert numbers from 1 to 15 into an array. And here is the code:

<html>
    <head></head>
    <body>
        <button id="myBtn" value="HELLO">HELLO</button>
        <script type="text/javascript">
            var btn = document.getElementById("myBtn");
            var num = null;
            btn.addEventListener('click', function() {
                var questions = new Array();
                num = Math.floor(Math.random() * 14 + 2);
                questions.push(num);

                for (var i = 1; i <= 15; i++) {
                    num = Math.floor(Math.random() * 14 + 2);
                    if (questions.indexOf(num) !== -1) {
                        alert(num + " Exists in array. So not pushing it");
                    } else {
                        alert(num + " is not found. So pushing it");
                        questions.push(num);
                    }
                    console.log(questions);
                }
                alert(questions);
            })
        </script>
    </body>
</html>

If you run this with the console open. You will notice that though a number is not in the array the in operator still discards the number without pushing. Can I know why and how to correct this?

And also is there any better way to insert x number of numbers in random order each time.

Upvotes: 1

Views: 84

Answers (2)

thefourtheye
thefourtheye

Reputation: 239453

You should not use in operator with Arrays. What you should have done is

if (questions.indexOf(num) !== -1) {

When you use in with an Array, it will not check the values but the indices of the Array. That is why your code fails.

Please check this answer of mine to know more about, why you should not use in operator with Arrays.

The best way to generate N unique random numbers is to, generate the list of numbers and then shuffle them, like this

function getRandomNumbers() {
    var rand, index = 0,
        array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

    array.forEach(function(value) {
        rand = Math.floor(Math.random() * ++index);
        array[index - 1] = array[rand];
        array[rand] = value;
    });

    return array;
}

console.log(getRandomNumbers());

This is adopted from the _.shuffle function of Underscore.js library, which shuffles the list of data with Fisher-Yates Shuffle algorithm.

Upvotes: 1

mgilson
mgilson

Reputation: 309891

the in operator works on objects, so you're really checking to see if your array has an index, not a value.

Upvotes: 1

Related Questions