0

I'm working on a codecademy.com lesson on arrays. I'm supposed to write nested loops to put each card of every suit in a deck of cards in an array.

I'm really messing this up. This is one combination that I've tried that doesn't work. The only indication that I have that I'm sort of close is that it returns "52" so at least 52 objects are going into the array. can anyone point out what I'm doing wrong?

   //array 1: the suits
var suits = ["clubs","hearts","diamonds","spades"];

//array 2: the ranks
var ranks = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"];

//using for loops, modify the "deck" array so that it becomes a 
//two-dimensional array that stores every card in the deck; 
//e.g. [1, "clubs"], [2, "clubs"],etc...["A", "spades"]
var deck = [];

for(i = 0; i < suits.length; i++){
    for (j = 0; j < ranks.length; j++){
        var cardArray = [];
        cardArray[0] = suits[i];
        cardArray[0][0] = ranks[j];
        deck.push(cardArray);
    }
}

2 Answers 2

2

Each iteration, a new array is being added to deck that looks like the following:

cardArray: [ [ ranks[j] ] ]

When cardArray[0][0] is set, it is overwriting cardArray[0] as an array with index 0 containing ranks[j]. Instead, set cardArray[0] to suits, and cardArray[1] to ranks.

cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);

This results in:

for (var i = 0; i < suits.length; i++){
    for (var j = 0; j < ranks.length; j++){
        var cardArray = [];
        cardArray[0] = suits[i];
        cardArray[1] = ranks[j];
        deck.push(cardArray);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I've edited my answer to show what you should have ended up with if you changed the code to reflect my answer. Here it is in action: jsfiddle.net/JUFdS/4
love how you made the table too
1

You should use a var declaration for your loop counter. Your problematic code is

cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];

which does things like

var foo = "clubs";
foo[0] = "J";

which obviously does not work. I think what you want is

var deck = [];

for(var i = 0; i < suits.length; i++){
    var cardArray = [];
    for (j = 0; j < ranks.length; j++){
        var twoCards = [];
        twoCards[0] = suits[i];
        twoCards[1] = ranks[j];
        cardArray.push(twoCards);
 //     // or the same thing as this loop body, shorter:
 //     cardArray.push([suits[i], ranks[j]]);
    }
    deck.push(cardArray);
}

2 Comments

about halfway down your code, you set twoCards[0] and twoCards[1] both to "suits". First time, suits[i], second time suits[j]. That's a typo, write?
@Michael: Yes, that was a typo. Thanks

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.