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

creating a function that sends two separate fetch requests with a pause in between each request

Currently, I am working with 2 endpoints. The first one requires a "post" request, and upon receiving the response, it should provide me with an ID that is used in the URL of the second endpoint. To ensure that I can obtain this ID before proceeding with ...

Unable to access frame: Error - Unable to retrieve 'add' property from undefined

I am working on customizing the chatbot functionality for my website built with Nuxt.js. I want the chatbot to display on certain pages while remaining hidden on others. Unfortunately, I encountered an issue when trying to hide it on specific pages. To im ...

Is there a way to transform individual data into a collective group dataset?

Here is the input data provided: data = [ { name: "John Cena", groupName: "WWE" }, { name: "Nandini", groupName: null }, { name: "Rock", groupName: "WWE" }, { name: "Vinay", groupName: null }, { name: "Rey Mesterio", groupName: "WWE" ...

Difficulty executing for loop due to multiple buttons, resulting in malfunctioning buttons in JavaScript code

Currently encountering an issue while trying to implement modal windows on my first website. Everything works fine without the for loop, but I wanted to have multiple buttons and windows, so I decided to use a for loop to handle each button. Strangely, the ...

An error of type 'TypeError' has occurred, where it is unable to access the property 'render' of an undefined element in

I'm using a function in my controller to render the "result" in my "home-page" view, which is calling my model to execute the query. exports.searchNoms = (req, res) => { getDatabaseModel.searchNoms(req).then(function(result) { console.l ...

What is the best way to declare a global variable while making an asynchronous call using AngularJS?

Is there a way to utilize the single_video variable outside of the controller function? The issue arises when attempting to access it in the second console.log, as it returns an 'undefined' error due to asynchronousity despite successfully printi ...

Steps for integrating Stanford's NLP into a web application

I have successfully developed a project utilizing Stanford's NLP API and models. Now, I am looking to integrate this Java-based project onto the web. After seeing the demo provided by Stanford-NLP, I am curious about the process they use to achieve th ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

Verify if a checkbox is selected upon loading the page

Hey there, I have a jQuery change function set up to turn an input text box grey and read-only when a user selects a checkbox. However, I'm interested in adding a check on page load to see if the checkbox is already selected. Any suggestions for enhan ...

Is it possible to integrate a collection of libraries along with external dependencies into Vite?

Currently, I am in the process of packaging a library for npm that uses type: "module". To accomplish this, I have configured vite's library mode with the following settings: export default defineConfig({ css: { postcss: { plugin ...

I can't seem to retrieve any values from the API other than "chicken"

Is there a way to make the search bar in my recipe app look for recipes that I provide, rather than fetching data from useState? Any suggestions on how I can achieve this? import React, { useEffect, useState } from 'react'; import Recipe from &ap ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

Analyzing viewer engagement by monitoring the duration of video watched using JavaScript

I need a way to monitor video views for individual users, using a table in the database called Viewings. Each viewing is associated with both a user and a video, and keeps track of the duration watched as well as the percentage of the video completed. Whe ...

Guide to incorporating WebElement scrolling in Selenium using Java?

I need to implement a scroll function for a table on my webpage rather than scrolling the entire page, so using window.scrollBy is not an option. After attempting to find the container responsible for the scroll functionality in the DOM (with no luck), I ...

Clones are made sortable instead of arranging them in a specific order

I have a list that can be sorted with some customizations. However, I am facing an issue where the items in the list get duplicated every time I try to sort them. When I pull one item to sort it, another copy gets added automatically. I am struggling to u ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Generating new objects from API request in React and aggregating them into a single, comprehensive object

I have developed a program that utilizes Axios to fetch data through API calls. I aim to save the fetched result as an object within my this.state.matrixDictionary variable. However, each time I make another API call, the previous object gets replaced. My ...

Ensure that the search input field is in focus whenever the showSearch state is true

Having difficulty focusing on the input field whenever the showSearch state is true. Utilizing useRef and useEffect for this purpose. When the showSearch flag changes, the useEffect hook is triggered to check if showSearch is true, and if so, it should foc ...

Tips on adjusting the label size of a radar chart in chart.js

My radar chart labels are appearing skewed and messed up on mobile devices, so I decided to scale them using the following code within ComponentDidMount(): const plugins = [{ beforeDraw: function(c) { var chartHeight = c.chart.height; c ...