0

I’m 100% certain this code has been working before. Now it strangely doesn’t.

The goal is to create a multiple choice quiz for a flashcard. I create an array to store the card's ids: the first one goes the current card id, then three other random ones. My goal is to make sure they don’t repeat either the first card or themselves.

This is how I do it:

    // Array of cards’ ids to use
    var randomCardsIds = [];

    // Get the active card’s element id, add it to the array
    randomCardsIds[0] = this.activeCardId;

    // Get the current cards collection
    var allCurrentCards = this.carouselEl.items.items;

    // Get three random ids of other cards
    var i = 0
    while (i<3) {

        // Get a random card element
        var randomCardEl = allCurrentCards[Math.floor(Math.random() * allCurrentCards.length)];
        // Get its id
        var randomCardElId = randomCardEl.body.down('.card').id;
        randomCardElId = randomCardElId.substring(randomCardElId.indexOf('_')+1);

        console.log(randomCardElId, randomCardsIds, randomCardsIds.indexOf(randomCardElId));

        // Make sure it is not in the array yet, and then add it
        if (randomCardsIds.indexOf(randomCardElId) == -1) {
            randomCardsIds.push(randomCardElId);
            i++;
        }
        // Otherwise, the loop will have to run again

    }

Basically, in a loop, for each item I check whether it already exists in the array or not. If it doesn’t, push it to the array, otherwise, run the loop again. Here is the console logging result:

enter image description here

Well, the first thing: it always shows the final state of the array: as if it is already filled with the results, which is weird. But the most important thing: the script does not recognise a duplicate (e.g. in the first result, 74 is repeated, and in the second to last, 47).

It only returns something different then -1, when it finds a match in the second position (returns 1, obviously). When a match is in a different position in the array, it always returns -1.

What am I doing wrong here?

Arnold
  • 2,390
  • 1
  • 26
  • 45

2 Answers2

0

Are you testing this in IE6? The problem is indexOf doesnot work with IE6.

For alternative you can check Best way to find if an item is in a JavaScript array?

Community
  • 1
  • 1
Vikram Shetty
  • 737
  • 7
  • 18
0

A variation on a shuffling algoruthm seems to be the best bet here.

hugomg
  • 68,213
  • 24
  • 160
  • 246