In JavaScript, the act of shuffling an array will produce consistent results

I have created a random array generator by shuffling an initial array multiple times.

SHUFFLE FUNCTION

const shuffle =(array) => {
    let currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array;
}

GENERATE CHROMOSOMES(This function creates an array of arrays that are shuffled from an initial one called "sequence")

const generateChromosomes = (numberOfChromosomes) =>{
    const result = [];
    const sequence = ["2", "3", "4"];

    for(let i = 1; i < numberOfChromosomes; i++){
        result.push(shuffle(sequence))
    }

    return(result);
}

Despite my efforts, each time I run the code, I seem to get the same array repeated 50 times. Subsequent runs give me another set of identical arrays. Any suggestions on why this might be happening?

Answer №1

It seems like the issue at hand is likely tied to how the array is being referenced. To resolve this problem, consider moving your sequence array inside the loop to ensure the reference is disabled and shuffle is set based on a static variable.

const generateChromosomess = (numberOfChromosomes) => {
    const result = [];

    for(let i = 1; i < numberOfChromosomes; i++){
        const sequence = ["2", "3", "4"]; // RELOCATE THE ARRAY HERE

        result.push(shuffle(sequence))
    }

    return(result);
}

There are several methods to remove the reference of the array:

JSON.parse(JSON.stringify(value))

OR

[...value]

OR (using lodash)

_.clone(array)

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

What could be preventing this src tag from loading the image?

Here is the file structure of my react project Within navbar.js, I am encountering an issue where the brand image fails to load from the Assets/images directory. import '../../Assets/Css/Navbar.css'; import image from '../../Assets/Images/a ...

First Impressions of Datatables

Is there a way to display a specific range of rows with Datatables initially? For example, showing rows 100-105 only. Does anyone know if this is achievable using the options available? ...

What's the deal with this route being a 404 error?

I'm currently working on incorporating a new route into Express, specifically for handling 404 errors. Despite my efforts to configure the route in a similar manner to others, I am encountering some difficulties. var repomapRouter = require('./ ...

Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? ...

Using JQuery to automatically scroll and anchor to the bottom of a dynamically populated div, but only if the user doesn't

I am attempting to achieve the functionality of automatically scrolling to the bottom of a div with the ID #chat-feed. The overflow for this div is set to auto, and I want it to remain at the bottom unless a user manually scrolls up. If they do scroll up, ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Different method for adding child elements to the DOM

When creating a DOM element, I am following this process: var imgEle = document.createElement('img');     imgEle.src = imgURL;             x.appendChild(imgEle); Instead of appending the last line which creates multiple img elements ev ...

Is there a way to display an animation when a page loads using jQuery that only plays for index.php and not other_page.php?

How can I trigger an animation on page load, specifically for my index.php page and not all other pages on my website? Is there a jQuery function that targets only the index.php page like this: $('index.php').ready(function()); If not, what i ...

Manipulate the label content of the last child using Javascript

On my BigCommerce website, I am trying to change the label text of a variable using a JavaScript function since the support team is unable to assist with this. Below is the code snippet that needs modification: <dd class="GiftCertificateThemeList" st ...

Guide on linking an id with a trigger function in HTML and JavaScript

In the snippet below, I aim to create a responsive feature based on user input of 'mute' and 'muteon'. Whenever one of these is entered into the textbox, it will change the color of linked elements with the IDs "text" and "text1" to red ...

Revise the list on the page containing MEANJS components

Utilizing MEAN JS, I am attempting to make edits to the list items on the page, but an error keeps appearing. I have initialized the data using ng-init="find()" for the list and ng-init="findOne()" for individual data. Error: [$resource:badcfg] Error in r ...

HTML steps for smooth scrolling to the top and bottom of a list

My HTML contains a vertical list with top and bottom arrows positioned nearby. I am looking to implement a function where clicking on the top arrow will move the list up gradually, and clicking on the bottom arrow will move the list down step by step. Belo ...

Removing a single object from an array of objects using MongooseJS

Hello to all the MongooseJS experts out there! I'm a newcomer to MongooseJS, and I've been trying to solve this problem for the past two days but haven't found a solution yet. Thank you in advance for any help! The Issue with My Delete me ...

The React.js Mui Collapse component exclusively triggers animation during the transition while closing, without any animation when expanding

Whenever I implement the Collapse component from Mui library in my projects, I face an issue where the transition animation only works when closing the component (when in={false}). However, when opening the component, there is a delay before the animation ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

Encountering difficulty in implementing two modals simultaneously on a single web page while utilizing the useDisclosure() hook in Ch

ChakraUI provides a custom hook called useDisclosure() which gives you access to isOpen, onClose , onOpen. const { isOpen, onOpen, onClose } = useDisclosure() You can use the onOpen function as an onClick handler for a button to open a modal. <Modal ...

Storing a portion of AJAX response as a PHP variable

Is there a way to store data received through an AJAX response in a PHP variable? I want to take the value of $('#attempts_taken').val(data[11]); and save it as a PHP variable. Any help would be great! <script type="text/javascript> $(do ...

Exploring the use of Shadow DOM in ContentEditable for securing text segments

I have recently been working on creating a basic text editor using ContentEditable. The main requirement for the application is to allow users to insert blocks of text that are protected from typical editing actions. These protected text blocks should not ...

The initial rendering of the NextJs 13 application is experiencing significant sluggishness when deployed on an EC2

After deploying my NextJS 13.4 app on an AWS EC2 instance with 2 GB of RAM, I noticed that the initial load time is quite slow, taking around 20 seconds to load for the first time. The development mode in NextJS builds and displays the result, which may co ...

Pulling JSON Data with Ajax Request

I am attempting to retrieve the following JSON Data: {"status":"success","id":8,"title":"Test","content":"This is test 12"} Using this Ajax Request: $.ajax({ url: 'http://www.XXX.de/?apikey=XXX&search=test', type: "GET", dataType: 'js ...