What is the best way to generate a loop that builds a full deck containing all 52 cards?

I am currently working on implementing a deck object in JavaScript, with two separate files - one for the card constructor and the other for the deck logic. My goal is to create a load function within the deck object that will populate the deck with 52 unique card objects, but I'm struggling with how to properly loop through to achieve this.

Here is the code snippet for the card constructor (card.js):

function card(pRank, pSuit){
    this.rank = pRank,
    this.suit = pSuit,
    this.used = false;
}

And here is the code snippet for the deck logic (deck.js):

deck = {

    cardArray: [],

    load: function(){
        for(i=0; i<52; i++){
           this.cardArray.push(card);
            };
        }
    }

Answer №1

When it comes to the next structure, here are some steps you can take:

const ranks = ['ACE', 'KING', 'QUEEN', 'JACK', '10', '9', '8', '7', '6', '5', '4', '3', '2'];
const suits = ['SPADES', 'HEARTS', 'DIAMONDS', 'CLUBS'];

function createCard(pRank, pSuit){
    this.rank = pRank,
    this.suit = pSuit,
    this.used = false;
}

const cardArray = suits.reduce((cards, suit) => { return [
        ...cards,
        ...ranks.map((rank) => new createCard(suit, rank))
    ]
}, []);

Answer №2

Clear and concise code example for creating a deck of cards in JavaScript.

var ranks = ['ACE', 'KING', 'QUEEN', 'JACK', '10', '9', '8', '7', '6', '5', '4', '3', '2'];
var suits = ['SPADES', 'HEARTS', 'DIAMONDS', 'CLUBS'];
var cards = [];
var m = 0;
var finalDeck = suits.map(function(i, j) {
  return ranks.map(function(k, l) {
    return new card(k,i)
  })
})

function card(pRank, pSuit) {
  this.rank = pRank,
    this.suit = pSuit,
    this.used = false;
}

console.log(finalDeck)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Three.js: Animation does not appear to be functioning

I have encountered an issue with animating an object that was exported using the blender plugin from Blender to THREE.js. The animation does not seem to start running as expected... Despite trying various combinations of settings during export from Blende ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...

Issues with Axios asynchronous operations

I'm facing a challenge with an axios call nested within another axios call, leading to asynchronous issues. Below is a simplified version of my code snippet: axios.all([ axios.get('https://foo..', { headers: { 'Content-Type ...

Ways to eliminate the index of the parent array from an array

Eliminating the parent array index within an array is my current objective. This is the array I am working with: Array ( [0] => Array ( [0] => Array ( [id] => 296 [u ...

PHP Matrix - Can you pinpoint where I might be going wrong?

Develop a program that will generate the following output: a 00000000 b 00000000 c 00000X00 d 00000000 e 00000000 f 000X0000 g 00000000 h 00000X00 12345678 The initial step of the program involves the user inputting a two-dimensional ...

Incorporating an additional table dynamically based on height considerations – can you provide visuals as guidance?

The visual representation of my question far surpasses my verbal explanation. My intention is to insert a new table once the height of the previous table exceeds a specific HEIGHT limit, not a certain number of rows. This project does not involve creat ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

Refresh the Rails HTML table with new data by incorporating ajax requests and vanilla JavaScript

I'm struggling to find a solution without using jQuery in my current scenario. How can I refresh a partial on my page without reloading the entire page? Within my new.html.erb file, there's a button that triggers a JavaScript function each time ...

"Sequencing time with Postgres, manipulating views with Angular

I am encountering issues with displaying graphs in AngularJS. My backend is written in nodeJS and includes an aggregator as a buffer for data received from netdata, which is then inserted into the database using a cron job. Now, with a new client request, ...

Retrieve user information from Auth0 once the user has completed the signup process

I am looking to integrate the ability to create new users on Auth0 through my admin panel. Currently, I am utilizing Auth0 lock for signups, but now I need to store these users in my Database, which requires their email and Auth0 user ID. I am exploring o ...

Transform mysql data in bulk to json format with php

I am struggling to convert a large amount of MySQL data into JSON using PHP. With over 20,000 records, I can't seem to successfully convert the MySQL data into JSON format for my REST API. Here is the code I have attempted so far: $query = mysql_qu ...

Getting started with Next.js, only to hit a dead end with a

After spending a week working on Next.js, I decided to test it outside of the development setup. Despite encountering some bugs, I was able to build and start it without any errors. However, when I tried to access http://localhost:3000, I received the foll ...

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...

Vue.js: Utilizing anonymous functions within props object

Looking to enhance the select2 example to make it more practical, I have added multiselect functionality and am now exploring custom select2 configuration options. Check out my progress on jsFiddle Encountering an issue where function properties of props ...

MATLAB issue: Unable to generate symbolic variables using an array loop

Having a specific cell array: MatrixF = {3x1 cell} {3x1 cell} MatrixF{1} ans = 'f1' 'f2 ' 'f3 ' MatrixF{2} ans = 'x1' 'x2 ' 'x3 ' The goal is to convert each item in the MatrixF arr ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

What is an example of when a 'do while loop' would be used in a practical scenario?

I have a good grasp of the operation of a do while loop, as it executes the code at least once before checking the condition. Can you explain the significance of using a 'do while loop' and provide some practical examples from everyday life? Ap ...

Tally the lines in the textarea

I have a textarea that allows users to input up to 16 lines of text. I created a directive for this purpose, and it works well when the user hits the enter key. However, I also want to restrict the input to only 16 lines, even if the user enters a very lo ...

the least amount of steps required to organize a list

Currently, I am working on a problem from Codeforces that involves sorting an array by either moving the elements to the beginning or the end of the array. Initially, I thought it was related to finding the longest increasing subsequence, but that approa ...