Element 0 is consistently absent from the random array selection

I have written a code that loads an excel file into a JavaScript array.

function Upload() {
        //Reference the FileUpload element.
        var fileUpload = document.getElementById("fileUpload");
 
        //Validating if the uploaded file is a valid Excel file.
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
 
                //For Browsers other than IE.
                if (reader.readAsBinaryString) {
                    reader.onload = function (e) {
                        ProcessExcel(e.target.result);
                    };
                    reader.readAsBinaryString(fileUpload.files[0]);
                } else {
                    //For IE Browser.
                    reader.onload = function (e) {
                        var data = "";
                        var bytes = new Uint8Array(e.target.result);
                        for (var i = 0; i < bytes.byteLength; i++) {
                            data += String.fromCharCode(bytes[i]);
                        }
                        ProcessExcel(data);
                    };
                    reader.readAsArrayBuffer(fileUpload.files[0]);
                }
            } else {
                alert("This browser does not support HTML5.");
            }
        } else {
            alert("Please upload a valid Excel file.");
        }
    };
    function ProcessExcel(data) {
        //Reading the Excel File data.
        var workbook = XLSX.read(data, {
            type: 'binary'
        });
 
        //Getting the name of First Sheet.
        var firstSheet = workbook.SheetNames[0];
 
        //Reading all rows from First Sheet into a JSON array.
        excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);
                localStorage["excelRows"] = JSON.stringify(excelRows);
                window.open("main screen.html", "Badge Draw - game");

    };

Whenever a button is clicked, the array is randomized, and the element at index [0] is displayed in a label.

    //loading the file into array
    memberDetails = JSON.parse(localStorage["excelRows"]);
    
    
    //randomizing the array
    for (let i = memberDetails.length - 1; i >= 0; i--) {
         const j = Math.floor(Math.random() * i);
         const temp = memberDetails[i];
         memberDetails[i] = memberDetails[j];
         memberDetails[j] = temp;
     }

    //getting the values stored at index 0
    memberNumber = memberDetails[0].Badge;
    memberName = memberDetails[0].Name;
     
    memberNumberLabel = document.createElement("label");
    var memberNumberText = document.createTextNode(memberNumber);
    memberNumberLabel.id = "memberNumber";
    memberNumberLabel.appendChild(memberNumberText);
    document.body.appendChild(memberNumberLabel);
    document.getElementById("memberNumber").setAttribute("style", "color: #000000; font-size: XXX-large; font-weight: bold; position: fixed; left: 40%; top: 40%");

    memberNameLabel = document.createElement("label");
    var memberNameText = document.createTextNode(memberName);
    memberNameLabel.id = "memberName";
    memberNameLabel.appendChild(memberNameText);
    document.body.appendChild(memberNameLabel);
    document.getElementById("memberName").setAttribute("style", "color: #000000; font-size: xxx-large; font-weight: bold; position: fixed; left: 40%; top: 60%");

}

There are only 6 elements in the array for testing purposes. However, after numerous tests, I've observed that the element at index [0] before randomization never appears. I can print the array and verify that all elements are present, but calling element [0] always seems to fail.

I believe it's a logical error but I'm unable to debug it myself.

Any assistance would be greatly appreciated.

Answer №1

Array shuffling technique utilized:

for (let i = memberDetails.length - 1; i >= 0; i--) {
    const j = Math.floor(Math.random() * i);
    const temp = memberDetails[i];
    memberDetails[i] = memberDetails[j];
    memberDetails[j] = temp;
}

To identify the flaw in the logic, let's examine a scenario with only 2 elements and run through the loop step by step.

When i is 1, Math.random() * i generates a value between 0 and 1, but due to Math.floor(), it always rounds down to 0 (since Math.random() never reaches 1). This results in swapping the elements at index 0 and 1.

When i is 0, Math.random() * i equals 0, causing us to swap the element at position 0 with itself.

The flaw lies in utilizing floor; replacing it with round may resolve this issue.

However!

If your goal is solely to select a random element from the array, you can achieve this more simply with:

const randomMember = memberDetails[Math.floor(Math.random() * memberDetails.length]

This method selects a random element without shuffling the entire 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

Using a vanilla JS object as a prop for a child component

I have created a custom Message class in my application to handle incoming messages, which is defined in message.js. Within message.js, I've implemented two classes: Message and EventEmit. The render function in my Message class requires passing an E ...

Is there a way to utilize local resources in case CDNs are unable to load properly?

Encountering an issue with Bootstrap and jQuery loading from CDN, sometimes failing to import from the CDN source. For instance: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYii ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

Accessing a JSON string correctly using JavascriptSerializer in JavaScript

When working with JavaScript, I encountered an issue where the data retrieved from a data table and converted to javascriptSerializer was not refreshing correctly when changing dataset selection parameters. The problem occurred when trying to populate a ne ...

What is the method for printing out the unique values present in two arrays?

I need to compare the values stored in filename[i] and filename[j], then print out the value in filename[i] that does not have the same filename as in filename[j. I am aware that it can be done using set_difference and a sort solution, but I am unsure of h ...

Remove objects from array that have any falsy key

Is there a way to filter this array to only include objects with truthy values for keys? For example, here is an array: [ { foo: NaN, test: 'String' }, { foo: 2, test: '' }, { foo: 3, test: 'Something' }, ] I want ...

Creating Self-Positioning Buttons within a Lineup

I need help creating self-deleting buttons. In the following code, I am generating a range of buttons within a for loop, adding them to a list, and arranging them in a grid. While I can remove any button at a specific index location from the list, I'm ...

Transform JSON data using jQuery from one format to a different one

I'm struggling to figure out the best way to convert a certain type of JSON data into an array. Do I have to manually traverse through all the data, or is there a map function that can help with this process? Any assistance would be greatly appreciate ...

How to efficiently upload multiple files in an array using jQuery and AJAX technology

Looking for a way to upload each file separately with HTML? <input type="file" name="[]" multiple /> Struggling to figure out how to achieve this? Here is an example: $('input:file').on('change', function(){ allFiles = $(th ...

The hyperlink function is not operational in Gmail attachments

Using an anchor tag to navigate to a specific section within the same page works perfectly when the HTML file is on my local machine. However, when I attach the file in Gmail and open the attachment, it doesn't work. Why is this happening? How can I m ...

Hide the Select Column from the material-react-table

Can someone help me with hiding specific columns in the material-react-table component? I've searched the documentation but couldn't find any relevant information. import { useMemo, useState } from "react"; import { MaterialReactTable } ...

python calculate quartiles and deciles for a 1-dimensional input array

I am looking to create a 1D dynamic array containing integer values and then display its decile values. The input is derived from live audio recording, where the RMS (average signal strength across the entire signal) is obtained using pyaudio. To constru ...

The tab contents are colliding and merging with each other, creating an overlap

I have created a code with two tabs that should appear when the tab header is clicked. However, there seems to be an issue where the content from the second tab is also previewing in the first tab when the page is loaded. Strangely, when I switch to the ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

javascript An interactive accordion component created with Bootstrap

I have been searching for a solution to create an accordion-style collapsible set of panels where the panels remain separate and do not have headers. I want buttons on one side, and when clicked, a panel is displayed on the other side. Only one panel shoul ...

What is preventing me from releasing dynamic memory?

UPDATE After some investigation, I discovered a logical error in the code snippet: if(carry == 0 && index < 0) exit = true; The issue arises when the shift value is less than 18 due to the initial segment length of 18 digits. This causes ...

What is the method to insert an array into another array at a specified location using numpy?

Just a quick question here. For example, I have x = [[1],[2],[3],[4],[5]] y = numpy.zeros((8, 1)) And I'm looking to achieve z = [[0],[0],[1],[2],[3],[0],[4],[5]] I am aware that the rows 0, 1, and -3 in array z will stay as 0 Another thing, is th ...

Having trouble with the Moment.js diff function in your React Native project?

Within my React Native application, I have implemented Moment.js and included the following code snippet: const expDate = moment(new Date(val)).format('MM-DD-YYYY'); const nowDate = moment().format('MM-DD-YYYY'); const diff = nowDate.d ...

Developing JavaScript regular expressions with exclusions within a specified range

The regular expression I am currently using ... var my_var = new RegExp('^[a-zA-Z0-9 ]+$') ... This regex selects characters a-z, A-Z, 0-9, and space while excluding all other characters. However, I now want to include '(', ')& ...

What is the process of passing a function into a custom react context provider that allows for state editing?

Below is the code snippet I am currently working with: import React, { useState } from 'react' export const NumberContext = React.createContext() export function NumberProvider({ children }) { const [numbers, setNumbers] = useState([]) fu ...