Revising variables in Java Script

How can I shuffle a list of variables in JS and maintain the order while changing their values? The following code snippet demonstrates what I am trying to achieve.

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

<script>
var gen = "male ";
var race = "white";
var rel = "christian";

var chars =[gen,race,rel];
chars = shuffle(chars); 

document.getElementById("demo").innerHTML = chars+"";

/*prints for example "white christian male" which is what I want

/*lets say I want to change the gender, and maintain the newly shuffled order (race-rel-gen in this case)*/ 

/* The below doesn't work. I want it to print "white christian female", but it just reprints the original string*/

gen = "female ";

document.getElementById("demo").innerHTML = chars+"";
</script>

Answer №1

If you wish to preserve the original order of your array, consider using an object instead of a string to maintain reference. Here is an example:

/* This function converts an array of objects into a formatted string */
const arrToString = (arr) => arr.map((obj) => obj.value).join(' ')

var gender = { value: "male" }
var race = { value: "white" }
var religion = { value: "christian" }

var characters =[gender, race, religion]
characters = shuffle(characters); 

// Output will be something like: "white christian male"
document.getElementById("demo").innerHTML = arrToString(characters);

// Changing the value of the 'value' key in the object
gender.value = "female"

// Output will now be: "white christian female"    
document.getElementById("demo").innerHTML = arrToString(characters);

Answer №2

If you want to manipulate data using a map, along with custom functions, here's how you can do it.

let character = new Map([
  ['gen', 'male'],
  ['race', 'white'],
  ['rel', 'christian'],
  ["order", shuffle([0,1,2])],
  ["display", ['gen', 'race', 'rel']]
]);

function shuffle(array) {
  return array.sort(_ => Math.random() > .5);
}

function display(mapItem) {
return mapItem.get("order").map(item => mapItem.get(mapItem.get("display")[item])); 
}

//display character
document.querySelector("#demo").innerHTML += "</br>" + display(character);

//change race
character.set("race", "blue");
document.querySelector("#demo").innerHTML += "</br>" + display(character);

// reshuffle order
character.set("order", shuffle(character.get("order")));
document.querySelector("#demo").innerHTML += "</br>" + display(character);
<p id="demo"></p>

Answer №3

It seems like the solution provided below should do the trick. By keeping the `person` object and the `order` array separate, you gain more versatility. I've opted to use Lodash for the `shuffle` function for added convenience.

Check out the CodePen Demo here

this.person = {
 gen: "male",
 race: "white",
 rel: "christian"
};

this.order = ["gen", "race", "rel"];

function display() {
  let temp = [];
  this.order.forEach((key) => {
    temp.push(this.person[key]);
  });
  document.getElementById("demo").innerHTML += temp.join(", ") + "<br>";
}

// shuffle the order of properties
_.shuffle(this.order);

// output initial data
display();

// make changes while retaining property order
this.person["gen"] = "female";
display();

this.person["race"] = "black";
display();

this.person["rel"] = "jewish";
display();

Answer №4

To update the array with a new variable value, you can follow this approach:

var gen = "male "
var race = "white "
var rel = "christian "

var chars =[gen,race,rel]
chars = shuffle(chars); 

document.getElementById("demo").innerHTML = chars+"";


gen = "female "
var chars =[gen,race,rel]
chars = shuffle(chars); 
document.getElementById("demo").innerHTML = chars+"";

You can view the code in action here: https://jsfiddle.net/AndrewL64/p6rgo01a/


Another way is to create a function for reusability:

function newVal(gen, race, rel) {
    var chars =[gen,race,rel]
    chars = shuffle(chars);
    document.getElementById("demo").innerHTML = chars+"";
}

newVal('male ','white ', 'christian ');

newVal('female','white ', 'christian ');

Check out the updated code snippet on jsFiddle: https://jsfiddle.net/AndrewL64/p6rgo01a/1/

Answer №5

Perhaps you've phrased your question incorrectly, or maybe your original intentions weren't fully conveyed in your inquiry. However, based on my understanding, it seems like you're searching for something along these lines:

var races = ["caucasian", "ethiopian", "malayan", "american", "mongolian"];
var beliefs = ["jewish", "buddhist", "muslim", "christian", "shintoist"];
var genders = ["male", "female"];

var randomArrayElement = function(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function makeCombo(r, b, g) {
  var race = randomArrayElement(r);
  var belief = randomArrayElement(b);
  var gender = randomArrayElement(g);
  return [race, belief, gender].join(" ");
}

document.querySelector("button").addEventListener("click", function(e){
  document.getElementById("profile-area").innerText = makeCombo(races, beliefs, genders);
})
<p id='profile-area'></p>
<button>Generate a profile</button>

Answer №6

It is important to create a shuffle function in your code. Here is an example implementation:

// Implement the shuffle function
function shuffleArray(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

Once you have defined this function, you can use it with an array of characters like so:

var characters = ["gen", "race", "rel"];

You can then display the shuffled array as a string by replacing the commas with spaces:

document.getElementById("demo").innerHTML = shuffleArray(characters).join(" ");

The join(" ") method is used to replace the comma with a space in the output.

Option 1) Reshuffle with new value(s)

If you want to change values in the shuffled array, you can do so by directly updating the elements:

characters[0] = "female";

To update the displayed content on the webpage, simply call the shuffle function again.

Option 2) Keep the shuffled order and output it with updated value

If you wish to maintain the shuffled order while updating values, store the shuffled array in a separate variable:

var characters = ["gen", "race", "rel"];
var shuffledCharacters = shuffleArray(characters);

document.getElementById("demo").innerHTML = shuffledCharacters;

// Update the value of 'gen'
shuffledCharacters[shuffledCharacters.indexOf("male")] = "female";

// Display the updated array
document.getElementById("demo").innerHTML = shuffledCharacters;

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 Dynamic Tree View Component in AngularJS Using JSON Data

I am new to AngularJS and I need help creating a TreeView Structure from a JSON Object. Here is an example of my Return JSON Object: var categoryTree = [{Name:'Item1', Childnodes : {}, id: 1}, {Name:'Item2', Childnod ...

Creating dynamic input fields from an array in PHP

Trying to wrap my head around this concept has been a challenge for me over the past week. I am in need of some guidance. My task is to generate dynamic form fields from PHP arrays. These arrays come in various sizes but are always simple. I want to crea ...

Exploring the process of sending various variables from PHP to a jQuery function

I have a jQuery function that prints charts using the jqPlot framework. I need to print multiple charts with different options, so I have to call this function several times with varying values. My current approach is not very elegant: //----- index.php: ...

`Where can I find instructions on splitting an item into a byte[]?`

Is there a better way to convert an object, specifically a Parcelable bundle, into a byte array? The method I was using seemed fine, but it turns out it wasn't as effective as I thought. Previously, this is how I was attempting to achieve it: public ...

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

The checkbox filter in Angular 6 has the ability to replace the previously selected

I've been working on creating a filter system using checkboxes. Below is a snippet of the code I'm currently using: filter.pipe.ts import { Pipe, PipeTransform, Injectable } from '@angular/core'; @Pipe({ name: 'filter2' }) ...

When populating data, two ID fields (_id and id) are generated as duplicates

Upon retrieving information from my database, I have noticed the presence of an additional id field alongside the standard _id field. These two fields consistently contain identical values. However, it seems that the id field appears only during population ...

Tips for automatically closing SweetAlert after an AJAX request finishes

I recently implemented Sweet-alert into my Angular project. function RetrieveDataFromAPI(url) { SweetAlert.swal( { title: "", text: "Please wait.", imageUrl: "../../app/app-img/loading_spinner.gif", showConfirmB ...

Leveraging HTTP/2 in conjunction with angularJS

As I was exploring ways to improve the performance of my web application, I came across HTTP/2. After learning about its features that can enhance website speed, I decided to implement it. Upon upgrading my browser to the latest version to enable HTTP/2 s ...

Eliminate duplicate items using the reduce method in JavaScript

Working with a set of Json Objects, I use a javascript map function to list each field along with an array of its possible types. For example: birthDate, [Date, String, String, String, String] isMarried, [Boolean, Boolean, Boolean, Boolean, String] name, ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

Sequencing numerous promises (managing callbacks)

I am encountering some challenges with promises when it comes to chaining multiple ones. I'm having difficulty distinguishing how to effectively utilize promises and their differences with callbacks. I've noticed that sometimes callbacks are trig ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

Vue is unable to capture Cordova events

Creating a hybrid app using Cordova while incorporating VueJS for routing and AJAX requests has presented some challenges for me. Despite my efforts, I have been unable to capture certain Cordova events. Even the essential deviceReady event seems to be el ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

New feature in jQuery inputmask enables placeholder text to be retained

I have integrated the inputmask feature from https://github.com/RobinHerbots/jquery.inputmask in my project, and I am applying the mask to all textboxes with the class "date". However, I am encountering a problem where if the user leaves one or more letter ...