Choose two items randomly from a list, remove them, and repeat this process until the list is empty. Refresh the list to start the process

As a complete novice in the world of coding, I'm seeking assistance to achieve a specific code. My goal is to randomly select an item from an array (in pairs) and continue this process until the user reaches the last item or 60 days have elapsed from using the service (possibly through a cookie). With some guidance from fellow users on StackOverflow, I've managed to put together a script that partially accomplishes this task.

`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];

var yourPics = [
  dogpics,
[   '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'   ],
[   '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'   ],
[   '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg'   ],
[   '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg'   ],
[   '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg'   ] //For example purposes, this array has been shortened to 52 cards
];

function get_random_number(array){
    return Math.floor(Math.random() * array.length |0);
}  // Despite attempting modifications based on other scripts like the one found here - https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty - success has eluded me

randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});

var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
  card.classList.toggle('is-flipped');
});
</script>`

Your help is greatly appreciated!

Answer №1

It's not entirely clear what you mean by "remove in pairs", but I'll provide an answer assuming you want to delete images ending in 02F.jpg and 02B.jpg together, followed by 03F.jpg and 03B.jpg.

To address this, I suggest organizing your data differently from the start. If these related images are connected, we could store them in a JavaScript object like so:

var imagePairs = [
  {
    bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', 
    fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
  },
  {
    bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', 
    fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
  }...]

This array now contains objects instead of simple strings. You can access the bImage property of an object with ease:

myPair = imagePairs[0]
myPair.bImage

If you wish to randomly delete one of these pairs, you can use the splice method.

randomlyDeletedPair = imagePairs.splice(randomIndexToDeleteFrom, 1)
removes one object at position randomIndexToDeleteFrom from imagePairs, presumably chosen randomly. The removed pair is assigned to randomlyDeletedPair.

I believe this object-oriented approach is more secure, ensuring that both related strings are deleted simultaneously.

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

How can I calculate the total of numerous sub matrices within a large matrix?

When dealing with a 2D matrix A, the goal is to determine the sum of the submatrix located between coordinates (x1,y1) and (x2, y2). An explanation was found that detailed how to calculate submatrix sums. While understanding most of it, there seems to be ...

The preflight request for OPTIONS is receiving a 400 bad request error on the secure HTTPS

When making an Ajax call on the front end and calling a WCF service through Ajax, I encountered an issue with adding headers. As a result, a preflight OPTIONS request is triggered but fails due to the URL being blocked by CORS policy. I tried adding the f ...

How can I manually include a triangle in BufferGeometry using Three.js?

Recently, I've been exploring the quickest method to change a mesh's vertices using three.js. Through my experimentation, I discovered that modifying parts of mesh.geometry.attributes.position.array and then setting mesh.geometry.attributes.posit ...

javascript trigger next input upon meeting condition

Currently, I am utilizing the jQuery liveform validation plugin to validate the input field based on a condition. The following code is used to automatically move to the next input field once the maximum input limit is reached. window.onload=function(){ ...

Component that dynamically changes background images in Vue

I'm currently working on a Vue banner that requires a dynamic background, but for some reason, it's not functioning as expected. I've experimented with different methods, and using an image tag like this works: <img :src="require(`@/asse ...

What is the best way to extract the elevation value (Z coordinate) from a mesh surface using X and Y coordinates in Three.js

Is there a way to determine the Z coordinate of a point in three js based on the known X and Y coordinates? I've attempted drawing a line at the X and Y points and finding the intersection with the mesh surface generated from a tiff file. However, I o ...

What is the best way to display information in a newly added row of a datatables table?

Working on ASP.NET gridview conversions with datatables.net plug-in. The reason behind this is complex and subject to debate. But, I need assistance with a specific issue. The process of converting the gridview using Javascript was simple and effective. H ...

The quickest regular expression match possible if it is already a subsection of another match

Is there a simple way to find the shortest match in a long text where strings are repeated? I'm having trouble because matches within already matched text aren't being found. Here's an example of the issue: Using code: "ababc".match(/a.+c ...

Hide the 1, 2, 3 page buttons in Datatables pagination and instead display only the Next and Previous buttons for navigation

I recently implemented datadables.net pagination for my HTML table. I am looking to customize the pagination buttons by hiding or removing the 1, 2, 3 ... buttons and only display Next and Previous Buttons. Is there a way to achieve this by setting paging ...

Could a potential concurrency issue arise when handling a Queue in JavaScript?

I am faced with a situation where I need to persist an array of properties via AJAX calls to a database. However, the current API does not allow sending the strings in batches, and simple looping will cause overwriting issues. To overcome this, I have impl ...

How can we best store the component's state in the URL in AngularJS?

I am working with a reusable widget that has its own state. This state includes the content of the search bar (2), one or more select boxes (1), and the tree where the user can pick the currently active element (3). My goal is to create a locationManager ...

Enhancing User Experience with React Hover Effects

I'm currently in the process of developing a React component library, and I'm looking to enhance the components with some stylish flair. Everything seems to be working smoothly, but I'm interested in changing the background color when a user ...

How can one determine the file position in a Node.js application? Simply by retrieving the value of lseek

When examining the usage of fs.read and fs.write in Node.js, it appears that direct exposure to the C function lseek is not provided; instead, the file descriptor's position can be modified just before any fs.read or fs.write operation using the &apos ...

Javascript inheritance concepts

Creating a set of classes in JavaScript to manage accounts presents a challenge for me. The main class is 'account', which serves as the parent class, while 'depositAccount' and 'savingsAccount' are its children. These classes ...

Enhance the information within the textextjs plugin by incorporating additional data

I am attempting to invoke a function within the textextjs method- //my function function GetAreaTags() { return "some text"; } //textext initialization $('#territory').textext({ plugins: 'tags prompt focus autocomplete ajax', ...

Validating data for Telegram Web Bots using JavaScript

Struggling with creating a user verification script for my Telegram web app bots. Need help troubleshooting. import sha256 from 'js-sha256' const telegram = window.Telegram.WebApp const bot_token = '<bot-token>' const data_check_ ...

Utilizing jQuery to Detect TAB Key Press in Textbox

I need to detect when the TAB key is pressed, prevent the default action from occurring, and then execute my custom JavaScript function. ...

What is the process for sending text messages in a local dialect using node.js?

Having an issue with sending bulk SMS using the textlocal.in API. Whenever I try to type a message in a regional language, it displays an error: {"errors":[{"code":204,"message":"Invalid message content"}],"status":"failure"} Is there a workaround for se ...

Imagine you are looking to execute an if/else statement

I'm having some trouble with this code that is meant to print different values based on certain conditions, but it only seems to be printing one value consistently. See the code snippet below: let twitterfollowers; let websitetraffic; let monthlyre ...

Building an Organized jQuery Mobile App with PhoneGap

Currently, I'm developing a game in phonegap using the jQuery Mobile framework. As my project has progressed, I've noticed that my code has turned into a tangled mess of spaghetti with one HTML file and several JavaScript classes. I'm curio ...