Shuffling decks of cards among players at a table using JavaScript

Seems like such a simple task, but I can't seem to get it right. The idea is to have an array of 8 other arrays, each containing sets of cards (although in this case, they just have random numbers). Depending on whether passDirection is set to -1 or 1, each array should shift by one position, creating a shifting effect for the playerList values.

However, instead of shifting properly, all arrays are getting replaced with the value at index 0, except for the first one. How do I correct this issue?

var playerList = new Array;
var passDirection = -1;

for(i = 0; i < 8; i++) {
  playerList.push([playerList.length,i]); // Populating Arrays with random data
}

for (i=0; i< playerList.length; i++) {
  console.log(i + ": " + playerList[i]); // Checking initial values
}

for(q=0; q < 5; q++){ // Repeating the process 5 times

  var bufferArray = playerList[0]; 

  for(i = 0; i < playerList.length && i > (playerList.length * -1); i += passDirection) {
      var catcher = i; 
      var passer = catcher - passDirection; 
      if (catcher < 0) {
          catcher = catcher + playerList.length;
      }
      if (passer < 0) {
          passer = passer + playerList.length;
      } else if (passer >= playerList.length) {
          passer = passer - playerList.length;
      }

      if (passer == 0) {
          playerList[catcher] = bufferArray;

      } else {
          playerList[catcher] = playerList[passer];
      }
  }

  for (i=0; i< playerList.length; i++) {
    console.log(i + ": " + playerList[i]);
  }
  console.log("...");
}

https://jsfiddle.net/3r1Lhwc5

Answer №1

Your code contains two mistakes that need to be corrected:

  • The expression if (passer = 0) is actually performing an assignment rather than a comparison. It should be changed to if (passer === 0).

  • Additionally, the passer index is being updated with the wrong direction of the value. Currently, your code is transferring values from index 1 to index 0 and then from index 0 to index 7 (or -1). This results in moving the same value during the second iteration. To fix this issue, you should modify passer = catcher - passDirection to passer = catcher + passDirection.

It's worth noting that these corrections can be achieved more efficiently by utilizing Array methods such as splice, shift, unshift, pop, and push on the main playerList array.

Answer №2

Simplify your life with the help of Array functions to shift elements from one end to another in an array. Implement this code snippet inside your loop:

if (direction === -1) {
    const firstElement = list.shift();
    list.push(firstElement);
}
else {
    const lastElement = list.pop();
    list.unshift(lastElement);
}

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

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

Is there a way to retrieve the headers from an HTTP response in JavaScript that wasn't initiated by an AJAX request?

I have a login page setup to send an HTTP post request to the server, which then redirects me to another page on the server in the response message. On this new page, I need to access the location header to obtain a specific value for future server tasks. ...

Ways to display a different landing page when navigating to the homepage of a website

In the Next application, I have set up a dynamic route at the root of my pages folder as src/pages/[page].js While this works smoothly for pages with slugs like example.com/my-page, it poses a challenge when trying to access a designated slug named homepa ...

Understanding how types intersect in TypeScript

I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions: {a:number}[] & {b:string}[] Does this result in {a:number, b:string}[] ? Any clarificat ...

Detecting collisions in Three.js

I seem to be overlooking something quite fundamental, as I can't seem to find a solution in the documentation or any other working code examples. I am currently creating a basic museum using THREE.js libraries. While most of it is set up, I need to im ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

The component fails to update even after changes are made to the Redux state

I currently have 4 buttons, each with a different color, and I want to display the last 10 button clicks as colors on 10 squares. The redux state is being used to map and display the square colors, which are also stored in localStorage. When a button is c ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...

Executing a JavaScript function within a Vue component script

I'm working on a simple component file for submitting a form, along with a JavaScript function to handle an action: <template> <div> <div class="modal-header"> <button type="button" class="close" data-dismi ...

Accept only numerical values, addition and subtraction symbols, commas, the F5 key, and various other characters

I want to restrict key strokes to only numbers (including those on the numpad), minus (-) and plus (+) signs, and commas (,). Currently, it types twice when I input a number (e.g. 2 is displayed as 22) and replaces the current value with the new number. F ...

Concealing the parent template in Vue Router when the child is displayed

Having some trouble setting up Vue.js with the router, specifically dealing with view display issues. I've created a router.js file with child routes for breadcrumbs and route clarity purposes. Each individual route loads perfectly fine when opened. ...

How can I update a specific element within an array of objects in JavaScript based on its reference rather than its index position?

I am dealing with multiple arrays of objects x=[ {a:1}, {b:2}, {c:3}, {d:4} ] y=[ {e:5}, {f:6}, {g:7}, {h:8} ] (etc) and I have a list of references pointing to the objects I need to replace. Instead of having an index into the array, I hold reference ...

jquery-ui allowing to resize child divisions as well

Currently, I am in the process of developing a website that includes resizable divs with jQuery. However, I have encountered an issue where only the width of the child divs is being resized when I adjust them. For reference, you can view the site and its c ...

Exploring the properties within a MongoDB document using mapping functionality

I am trying to retrieve data from a document using Node.js and encountering an issue where the map operator is returning data with similar names twice. I am wondering if I can use filter instead of map to address this problem. Here is the code I am using t ...

Is there a text form in Angular that allows only numerical input?

Here's an input form in Angular that I'm working on: <input ng-model="sc.zip" class="form-control" maxlength="5" type="text" /> I want to keep the form as a simple empty textbox without limiting it to only numbers. However, I do want to r ...

Sending a request in Vue.js and not receiving a defined response

As a beginner in VueJs and Expressjs, my goal is to create the frontend using Vuejs and backend using ExpressJs. When I send a post request to the backend (ExpressJs), I encounter the following issues: 1- Response from the server is undefined. 2- In Chrom ...

Ensuring nested JSON key existence before rendering in React

When retrieving data from MarvelAPI, there is no certainty that the key being accessed will be available. Therefore, I am implementing if statements to check each key before accessing them. The current code below appears quite messy. Is there a more effic ...

Issue with Node.js MongoDB collection.find().toArray not returning results

Despite coming across questions similar to mine, I struggled to resolve the issue independently. Within my '../models/user' model, my goal is to retrieve all users and store them in an array, which will then be returned to the controller for fur ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...