Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Practice Basic Arrays in JavaScript!
You have completed Practice Basic Arrays in JavaScript!
Preview
Use nested loops to build a multi-dimensional array.
Resources
- Fisher-Yates Shuffle Alogrithm
- Treehouse course: JavaScript Array Iteration Methods
Complete code
// 1. Add a for loop -- to loop through each element in the suites array
// 2. INSIDE that loop, add another loop that loops through elements in the ranks array.
// 3. Inside the second, nested loop, create a new array named card, which is composed of a rank and a suite. For example ['King', '♥︎'].
// 4. Push that card onto the deck array. Once both loops complete running, the deck array will hold 52 elements, and each of those elements are themselves an array.
// 5. Finally, pass the new deck to the shuffle() function, and return the results.
function createDeck() {
var suites = ['♠︎','♣︎','♥︎','♦︎'];
var ranks = ['Ace','King','Queen','Jack','10','9','8','7','6','5','4', '3','2'];
var deck = [];
// add your code below here:
for (let i=0; i<suites.length; i++) {
for (let j=0; j<ranks.length; j++) {
let card = [];
card.push(ranks[j], suites[i]);
deck.push(card);
}
}
return shuffle(deck);
}
// 6. Call the createDeck() function and store the results in a new variable named myDeck
let myDeck = createDeck();
/* 7. Use a for loop to loop through the deck and list each card in the order the appear in the newly shuffled array. Use the log() method to print out a message like this, once for each card:
"7 of ♥.︎"
*/
for (let i = 0; i<myDeck.length; i++) {
console.log(myDeck[i][0]+ ' of ' + myDeck[i][1]);
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
a while and
are now ready to see how I did it.
0:00
Let's jump in.
0:02
In this project you're supposed to
create a function named createDeck,
0:03
that builds a two dimensional array,
a deck of cards.
0:07
You need to use two nested for
loops to do it.
0:11
It's a good challenge, so
let's take a look at it.
0:14
We started out with a function for
shuffling the elements in an array.
0:17
It uses the Fisher-Yates
shuffle algorithm.
0:24
See the teacher's notes for links for
more information on this, but
0:27
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up