Mix up and present cards for a game of blackjack (Javascript)

Have you noticed why "card2" is randomly adding an object to the array? It should consistently add objects to the array.

const cards=[
  {
    card: '&#127137',
    value: '1'
  },
  {
    card: '&#127138',
    value: '2'
  },
  {
    card: '&#127139',
    value: '3'
  },
  {
    card: '&#127140',
    value: '4'
  },
  {
    card: '&#127141',
    value: '5'
  },
  {
    card: '&#127142',
    value: '6'
  },
  {
    card: '&#127143',
    value: '7'
  },
  {
    card: '&#127144',
    value: '8'
  },
  {
    card: '&#127145',
    value: '9'
  },
  {
    card: '&#127146',
    value: '10'
  }
];

var deck = [];

shuffleDeck = () =>{
    var tempDeck = [...cards];
    var card1 = [0];
    var card2 = [0];

    while(0 !== tempDeck.length) {
        var randomIndex = Math.floor(Math.random() * tempDeck.length);
        card1 = tempDeck.splice(randomIndex, 1);
        card2 = tempDeck.splice(randomIndex, 1); 
        deck = [...card1, ...card2];
      }
}
shuffleDeck();

 for(var i = 0; i <= deck.length; i++){
     console.log(deck[i]);
} 

Answer №1

There are a couple of issues that need to be addressed in the code:

  1. The first issue is with setting the randomIndex variable only once in the while loop, which leads to an error when trying to set both card1 and card2. Since splice removes the index from the array, it causes card2 to be undefined.
    SOLUTION: Reset the value of randomIndex after setting card1.

  2. The second issue lies in the for loop condition where it should be i < deck.length instead of i <= deck.length. This change will prevent accessing an undefined value since the length of the array does not include an index of 2, only 0 and 1.

const cards = [{card: '&#127137', value: '1'}, {card: '&#127138', value: '2'}, {card: '&#127139', value: '3'}, {card: '&#127140', value: '4'}, {card: '&#127141', value: '5'}, {card: '&#127142', value: '6'}, {card: '&#127143', value: '7'}, {card: '&#127144', value: '8'}, {card: '&#127145', value: '9'}, {card: '&#127146', value: '10'}];

var deck = [];
shuffleDeck = () =>{
  var tempDeck = [...cards];
  var card1 = [0];
  var card2 = [0];

  while(0 !== tempDeck.length) {
    var randomIndex = Math.floor(Math.random() * tempDeck.length);
    card1 = tempDeck.splice(randomIndex, 1);

    randomIndex = Math.floor(Math.random() * tempDeck.length);
    card2 = tempDeck.splice(randomIndex, 1); 
    deck = [...card1, ...card2];
  }
}

shuffleDeck();

for(var i = 0; i < deck.length; i++){
     console.log(deck[i]);
}

Answer №2

It seems like the question could use some clarification... while reviewing your code, I noticed that the issue might lie in this line deck = [...card1, ...card2];. Since you are within a loop, you are only adding 2 cards at a time to your new deck, causing the last values to be ignored and overwritten in the next iteration. You should utilize deck.push to add new cards to the deck.

const cards=[
      {
        card: '&#127137',
        value: '1'
      },
      {
        card: '&#127138',
        value: '2'
      },
      {
        card: '&#127139',
        value: '3'
      },
      {
        card: '&#127140',
        value: '4'
      },
      {
        card: '&#127141',
        value: '5'
      },
      {
        card: '&#127142',
        value: '6'
      },
      {
        card: '&#127143',
        value: '7'
      },
      {
        card: '&#127144',
        value: '8'
      },
      {
        card: '&#127145',
        value: '9'
      },
      {
        card: '&#127146',
        value: '10'
      }
    ];

    var deck = [];

    shuffleDeck = () => {
        var tempDeck = [...cards];
        var card1 = [0];
        var card2 = [0];

        while(0 !== tempDeck.length) {
            var randomIndex = Math.floor(Math.random() * tempDeck.length);
            card1 = tempDeck.splice(randomIndex, 1);
            card2 = tempDeck.splice(randomIndex, 1); 
            deck.push(...card1, ...card2);
          }
    }
    shuffleDeck();
    
    for(var i = 0; i < deck.length; i++){
         console.log(deck[i]);
    } 

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

Struggling to extract text from within a <p> tag on an Ionic 1 app page on iOS

After developing an ionic-1 application for iOS and Android devices, I encountered an issue with displaying mobile numbers in one of the views. The numbers are contained within <p> tags. While users can click and hold on a number to copy it on Andr ...

I am currently developing a program that is displaying a blank page despite my efforts to write

I've been trying to write the code below but it only shows a blank page. var greeting = React.createClass({ render: function() { return ( <div> <h1>Hello</h1> </div> ...

Firebase Firestore is returning the dreaded [object Object] rather than the expected plain object

I've created a custom hook called useDocument.js that retrieves data from a firestore collection using a specific ID. However, I'm encountering an issue where it returns [object Object] instead of a plain object. When I attempt to access the nam ...

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Show or hide specific elements based on parameters using ng-show in Angular

One challenge I am facing is how to manage a menu with multiple buttons that open submenus without using a massive switch statement in my code. Instead, I want to try something different: In the HTML file, I call the function toggleVis and pass the nam ...

What is the best way to structure a JSON response in python code?

Here is a sample of my JSON data: data = [{"document_id":"FT_3860001798686","party_type":"1","name":"LEE, GABRIEL"},{"document_id":"FT_3860001798686","party_type":&qu ...

Utilizing Cordova for Windows 8.1 in Visual Studio 2015 for external image retrieval and insertion into img tag

I am encountering an issue with displaying external images in a Cordova app. While the DOM is functioning correctly, the images are failing to load. I am specifically trying to resolve this for Windows 8.1 only. In my Cordova project for JavaScript, I have ...

Loop through each item in the JSON object

After making an ajax call, I receive a json object in the success callback with the following structure: {test 1: Array(2), test 2: Array(3), test 3: Array(2)} The arrays inside each key have elements that look like this: 0: {IdProduct: "1", ProductName ...

Error in React Component Library: The identifier 'Template' was not expected. Instead, '}' is expected to end an object literal

I've embarked on the exciting journey of creating my own React component library. Utilizing a helpful template found here, I've shaped the latest iteration of my library. To test its functionality, I smoothly execute the storybook with yarn stor ...

Searching DynamoDB in node.js using mapped items

In my DynamoDB table, I am trying to retrieve all Items where the Review.ID matches 123. Item: { id: 1, review: { Id: 123, step1: 456, step2: 789, step3: 1234, }, // Add more items here }, Item: { id: 2, review: { Id: 123 ...

Is there a way to launch Visual Studio Code using a web browser?

Is there a way to launch "Visual Studio Code" automatically upon clicking a button on my website? ...

How about implementing built-in validation for Vue Headless UI Listbox (Select) element?

I need assistance in integrating native validation support into the Vue3 or Nuxt 3 Vue Headless UI Listbox (Select) component. It appears that direct support is not available, so I am looking for the best and most straightforward approach to achieve this. ...

Obtaining the ID from a URL in node.js

As a newcomer to the world of Javascript and node.js, I am venturing into creating a REST API with URLs structured as follows: /user/{userId}/docs The goal is to extract the value of {userId}, which, for instance, in the URL /user/5/docs would be 5. Wh ...

Any suggestions on how to address vulnerabilities in npm when upgrading the main dependency version is not an option?

I recently ran the npm audit --production command and found a high-risk vulnerability related to the snowflake-sdk dependency. After checking the snowflake github page, I noticed that the package.json file includes "requestretry": "^6.0.0&qu ...

What is the process for creating a clickable file upload in Angular?

Currently, I am utilizing the instructions found in this guide to implement a file upload feature in my project. The code provided works perfectly: <input type="file" class="file-input (change)="onFileSelected($event)" #fileUplo ...

Modify the background color of a div by selecting a hex code from a dropdown menu

Is there a way to utilize jQuery in order to alter the background of a <div> by choosing the HEX code from a separate dropdown menu? HTML <select id="target"> <option value="#c2c2c2">Grey</option> <option value="blue">Bl ...

What could be the reason behind the app.get middleware not functioning properly following the app.use middleware in ExpressJS?

My server.js file includes the following code. However, I've encountered an issue where the code in app.get() function works fine when the app.use() middleware is commented out. But, when both are included, the get request doesn't seem to run. An ...

Is there a way to retrieve the redirected URL from an AJAX request?

Hi everyone, I'm currently trying to solve a puzzle regarding how to identify whether a PHP script redirects during an AJAX call. Does anyone have insight into whether JQuery AJAX has the capability to detect and keep track of location changes? Let&a ...

Save the array as a variable in your JavaScript code so that you can easily access it

I am currently working on generating a list only when a specific page is visited using JS/jQuery. I then need to be able to access this list when navigating to other pages and retrieve the variables within it. How can I effectively store this list? Initia ...