JavaScript - Shuffle Cards Memory Game Function

I've been working on developing a memory game using JavaScript, and I've encountered some challenges along the way. After successfully designing the HTML and CSS components, my focus has now shifted to implementing the JavaScript functionality. One key aspect of the game involves assigning randomly generated images to pairs of cards from an array containing image sources. However, I've noticed that when I execute the shuffleImages() function, the resulting image pairs are not always consistent, with some appearing in odd numbers rather than even pairs as required for the game.

This issue leads me to the following question: How can I ensure that the images assigned are always in even pairs? It's important to note that I am relatively new to JavaScript and have only been coding for about two weeks.

Any guidance or suggestions would be greatly appreciated.

Here is the HTML/CSS/JavaScript code snippet:

Answer №1

Start by creating a new array with each image duplicated:

const doubledImages = [];
for (let i = 0; i < images.length; i++)
    doubledImages.push(images[i], images[i]);

Next, rearrange the elements in this array using the method described in How to shuffle a JavaScript array randomly?

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

The function and if-else statement are experiencing malfunctions

Currently in the early stages of learning coding, I've been focusing on building a solid foundation by practicing with CodeWars. Utilizing this platform for practice has been beneficial because it offers solutions for guidance. While attempting to wor ...

When attempting to print a Bootstrap 4 HTML page in Chrome, the browser headers and footers are being clipped

Currently experiencing an issue with printing an HTML page styled using Bootstrap 4 (Bootstrap 3.3.7 works fine) on Chrome where the header and footer are partly covered up. Take a look at this screenshot to see what I mean - the date, title, and file/url ...

Incorporating both an href link and PHP code using a single click event on a submit button

After exploring various forums, I am still struggling to solve this issue. Can someone please assist me in understanding how to achieve this? When I click the submit button, it currently directs me to a file location via a link without any issues. Howeve ...

Design a clickable div element embedded within an interactive article using HTML5

Currently, I am facing an issue with placing clickable div elements inside an article tag in HTML5. The problem is that when I try to click the divs, it registers as a click on the article itself. Below is an example of my code: HTML: <article id=&apo ...

I have noticed that the display:none property for <span> elements does not seem to work in IE8 on some computers, although it does

<span id='x' style='display:none;'> <input type=button value='x'> </span> <span id='y' style='display:none;'> <input type=button value='y'> </span> Although th ...

Breaking down the text field into two distinct fields

I have successfully modified the code below to meet a new requirement. The current functionality involves splitting the Price field into Pounds and Pence based on the index of the . symbol. However, I now need to extend this functionality to split a Name ...

Display the value in multiple constant declarations

Related code: window.onload = function calcPrice() { for(const cloud of Array.from(document.getElementsByName("cloud"))) { fetch("_config/get_value.php?id="+cloud.getAttribute("cloudid")+"&periodicity=monthly") .then(res => res.text()) ...

What is the most efficient way to access a cell within an HTML table using jQuery or the Document Object Model (

I have an unchangeable HTML table styled with CSS. My goal is to extract the value from the first column for filtering purposes. I've been struggling to locate a suitable jQuery or DOM function to accomplish this task. Unable to find a way to access ...

Transferring blank documents to a React-Native server

When attempting to send JSON files to the server using NodeJS with multer, I am running into an issue where the files are being sent empty. Currently, I am utilizing React-native-File-System to iterate through all the files located in the specified folder ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

Having trouble persisting and displaying information in MongoDB with Mongoose

app.post('/contact', (req, res)=> { var myData = new Contact(req.body); myData.save().then(()=>{ res.send("Item has been saved"); }).catch(()=>{ res.send('Item was not saved due to some error'); ...

Exploring the various methods of creating controllers and services in AngularJS and understanding the rationale behind each approach

I've been observing various instances of controller and service creation in AngularJS and I'm feeling perplexed. Could someone elucidate the distinctions between these two methods? app.service('reverseService', function() { this.re ...

Issues with Angular Modals not responding to ng-click commands

I created a modal using Angular, and it pops up correctly. However, I am facing an issue where the exit button does not work to close the modal. It functions properly when the button to open is clicked again, but adding a new button inside the modal does ...

The custom CSS cursor appears to be displaying in a pixelated manner

Trying to experiment with custom cursors, but every attempt ends up pixelated. I created a ring asset to demonstrate the issue. Here is the cursor image file. cursor: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/272259/circle.png), auto; Although it ...

"During the testing phase, the req.body object is found

I'm currently performing unit testing on my express application using Mocha and Chai. However, when I attempt to use req.body in the test file to parse the object, I only receive undefined in the testing results. In my server (app.js), I have alread ...

In JavaScript, what does this condition signify? if(display or true, then

The display option is not required in the function, but I am confused about its usage with || true Which part of the code actually evaluates this condition? if(display || true){...} if(display || true){ $("#container").fillContent(this.showReport(this.t ...

Step-by-step Guide to Setting pageProps Property in Next.js Pages

When looking at the code snippet provided in .../pages/_app.js, the Component refers to the component that is being exported from the current page. For instance, if you were to visit , the exported component in .../pages/about.js would be assigned as the ...

What is the best way to replicate tags in selenium when an element has multiple class names?

Extracting information from a webpage where a significant amount of text was concealed behind the "see more" tab. Using selenium to click on all such buttons and then extracting data with beautifulsoup. However, some of these buttons have additional space ...

Tips for using res.json as a callback function

When using a function with a callback parameter, I found that this method works perfectly fine: DB.last(user,(data) => res.json(data)); However, when attempting to refactor it for better readability as shown below: DB.last(user,res.json); The structu ...

WebWorker tends to be loaded intermittently on android devices

We have integrated a web worker in our Ionic application to handle certain computations. Previously, this setup functioned properly without any issues. However, suddenly we are encountering some challenges. Despite making significant changes throughout th ...