Guide to shuffling an array with a simple click of a button

To simplify, I have an array that I would like to randomize by clicking a button. Once randomized, I want to display the first result from the array with another button. The array is currently randomized when opened in Chrome, and checking the results in the inspection window shows that the randomization is working with the button.

However, there is another button for printing the first result on the screen. Currently, it prints in a separate window, which is an issue to address later.

In essence, the randomize button seems functional in the inspection window but not when attempting to use the print button.

Here is my code :

const magicitems = [];
magicitems[0] = "hammer ";
magicitems[1] = "gaunlet ";
magicitems[2] = "cloak ";
magicitems[3] = "chalk ";
magicitems[4] = "- ";

//shuffling the array with a command, is specific?//// i have no real idea what this bit means//
const Shuffle = magicitems => {
  for (let i = magicitems.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = magicitems[i];
    magicitems[i] = magicitems[j];
    magicitems[j] = temp;
  }
  return magicitems
};
Shuffle(magicitems); //shuffling magic items//


var RandomItem = magicitems[0]; //making a var that is 1 item from magicitems//

const print = document.getElementById("demo").innerHTML = magicitems;
//printing the array was the first thing i did before the shuffle, now i shuffle first and am trying to print RandomItem to get 1 random item from the array//
// it worked, now i am trying to make a button that will do document.getElementById("demo").innerHTML = RandomItem; on a click instead of command
//after i made the button, the const print was no longer needed to put the result on the screen
<h2>random magic item</h2>

<p id="demo"></p>

<button type="button" onclick="Shuffle (magicitems)">random</button>
<button type="button" onclick="document.write(RandomItem)">print</button>

The array actually has 165 items so I reduced that for readability purposes. The concept remains the same - shuffling the array when clicking random and displaying the result in the same window upon pressing print.

Answer №1

The main issue lies in the fact that the RandomItem variable is not being updated after the array has been shuffled. Once this aspect is addressed, the implementation functions correctly:

//creating an array of magic items//
const magicitems = [];
magicitems[0]= "hammer ";
magicitems[1]= "gaunlet ";
magicitems[2]= "cloak ";
magicitems[3]= "chalk ";
magicitems[4]= "- ";

//applying a shuffle command to randomize the array//
const Shuffle = magicitems => {
for (let i = magicitems.length - 1; i > 0; i--){
const j = Math.floor(Math.random() * (i + 1));
const temp = magicitems[i];
magicitems[i] = magicitems[j];
magicitems[j] = temp;
}

RandomItem = magicitems [0];
return magicitems
};
Shuffle (magicitems); //shuffling magic items//

var RandomItem = magicitems [0]; //creating a variable for one item from the magicitems array//

const print = document.getElementById("demo").innerHTML = magicitems;
<h2>random magic item</h2>

<p id="demo"></p>


<button type="button" onclick="Shuffle(magicitems)">random</button>
<button type="button" onclick="document.getElementById('demo').innerHTML=RandomItem">print</button>

RandomItem is declared as a global variable, allowing it to be accessed within the shuffle function. Simply updating it when the shuffle function is executed resolves the issue.

Answer №2

function mixUpArray(arr) {
  return arr.sort(() => Math.random() - 0.5);
}

const mythicalItems = ["sword", "amulet", "staff", "ring"];

const mixedArray = mixUpArray(mythicalItems);

const chosenItem = mixedArray[0]; // <- Remember to select the first item from the shuffled array, not the original one.

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

Tips for using JavaScript to style an array items individually

I have currently placed the entire array within a single div, but I would like to be able to display each element of the array separately so that I can style "date", "title", and "text" individually. This is my JSON structure: [ { "date": "Example ...

JavaScript for validating forms in PHP

Hey everyone, I'm struggling to understand why the alert box isn't showing up when I run this code. I'm new to programming and find HTML easy, but I'm currently in a PHP class where we have been tasked with creating and validating a for ...

Storing a variable in jQuery using AJAX and retrieving it at a later time

Hey there! I'm currently using jQuery and AJAX to fetch the user ID of the logged-in user. I'm storing this information in a variable so that I can use it for some logic later on. However, I'm facing issues with accessing it. Here's my ...

Aborting HTTP POST requests in IE due to error code 0x2ee2

Currently, I am utilizing angularjs for file uploads to my API. The page features a multi-file select option where users can choose one or multiple files. Upon selection, the page initiates calls to the api and uploads each file individually using requests ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

"What could be the reason why the color property is not being applied to this

I have been attempting to change the color of an icon by using the color property, but for some reason, it is not applying as expected. Here is the code snippet I am working with: "& .MuiListItemIcon-root": { color: "red" }, ...

Is there a way to retrieve the text of a clicked button with execute_script?

Is there a way to extract text from a clicked button and send it back to Python? The user clicks the button in the Selenium WebDriver browser using the mouse. This is what I attempted: x=driver.execute_script("$(document).click(function(event){var te ...

Virtual machines have encountered issues when attempting to utilize setTimeout within the browser with vm.runInNewContext

When running a JS script using the vm module in a browser, the following details are included: vm.runInNewContext(codeToEval, sandboxObject); Although interval methods like setTimeout and setInterval do not work, even when exposed in the sandboxObject cr ...

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

Send an array of JSON objects representing table rows to an MVC controller

I was attempting to find a solution for a problem. Within the View: var data = [{ "MissionSheetMasterId": MS_MasIds, "EmployeeId": EmpIds, "PaidQty": Qtys, "PaidAmount": Amount }]; console.log(data); $.ajax({ url: '@Url.Action(" ...

Ways to extract all values following a specific character in a list or array

Suppose we have a list like this: data = ['O', 'O', 'B', 'I', 'I', 'B', 'I', 'O', 'B', 'I'] The goal is to extract every index after B (including B) until ...

"Can you explain the concept of an undefined id in an AJAX request

Within my mongodb database, I have two Tables: GstState Store While working on my Store form, I encountered an issue where the JSON response was returning an undefined id when trying to select a state based on country via an ajax call to fetch GstStates ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Creating a Cross Fade Animation effect with the combination of CSS and JavaScript

I've been attempting to create a similar animation using html and css. Below gif shows the desired outcome I am aiming for: https://i.sstatic.net/YsNGy.gif Although I have tried the following code, I have not been able to achieve the desired result ...

Transform an array of arrays object with multiple depths into an array of objects

Having some difficulty with the conversion of an array of arrays-like object into an array of objects. The reduce method is being used, and it successfully converts the array data to an object for the first set of arrays. However, on the second iteration, ...

Require assistance in understanding JSON data in the form of a variable

Apologies for any language barriers, but I have encountered a problem that I need help with. I am trying to create a highchart from an AJAX call. The following code works perfectly: chartOptions = { chart: { renderTo: 'grafica1', type: 'ar ...

The socket.rooms value is updated before the disconnection listener finishes its process

When dealing with the "disconnect" listener, it's known that access to socket.rooms is restricted. However, I encountered an issue with my "disconnecting" listener. After making some modifications to my database within this callback, I attempted to em ...

Conflicting behavior between jQuery focus and blur functions and retrieving the 'variable' parameter via the $_GET method

There is a simple focus/blur functionality here. The default value shown in the 'Name of Venue' input field changes when the user clicks on it (focus) and then clicks away(blur). If there is no text entered, the default value reappears. Input fi ...

Manipulate text with jQuery

Is there a way to remove 'http://' or 'https://' from text using javascript? I am looking for regex solutions as well. This is what I have tried so far: JSFIDDLE HTML: <div class="string"></div> JS: $text = $('.s ...

Troubleshooting Rails 4: Handling a 404 Not Found Error When Making an AJAX Call to a

After spending about an hour trying to figure this out, I am still stuck... The action in my oferts_controller.rb file looks like this: def update_categories @categories = Category.children_of(Category.find(params[:categories])) respond_to ...