Utilizing Math.random to extract unique names from an array without any duplicates

I have a task to select three unique names from an array and store them in a new array. However, I am facing an issue where the same names keep getting randomized instead of finding new ones.

If you want to see the code in action, check out this jsfiddle script.

Code:

findStudentBtn.onclick = findStudent;

function findStudent() {
    var studArray = ["John","Daniel","Hans","Lars","Tom","Amanda","Jane","Sarah"];
    for (i=0; i<3; i++) {
        if (i === 1) {
            var randomStud1 = studArray[Math.floor(Math.random() * studArray.length)];
            msg8.innerHTML += randomStud1 + ", ";
        }
        if (i === 2) {
            var randomStud2 = studArray[Math.floor(Math.random() * studArray.length)];
            msg8.innerHTML += randomStud2 + ", ";
        }
        if (i === 3) {
            var randomStud3 = studArray[Math.floor(Math.random() * studArray.length)];
            msg8.innerHTML += randomStud3 + ", ";
        }

        if (randomStud1 == randomStud2 || randomStud2 == randomStud3 || randomStud1 == randomStud3){
            msg8.innerHTML = "";
            findStudent();
        } 
    }
}  

Answer №1

If you're curious about the solution but don't want to navigate to the jsfiddle, here's the script I implemented.

findStudentBtn.onclick = function(){
    findStudent();
};

var r_stud = ["John","Daniel","Hans","Lars","Tom","Amanda","Jane","Sarah"];
var r_rndm = [];
var r_newr = [];

function getStudent(){

    //Handling cases where available choices are insufficient for selecting 3 students.
    if(r_rndm.length == r_stud.length){
        //Resetting the array of randomly selected students
        r_rndm = [];
        return r_newr;
    }

    //Selecting a student at random
    var i_randomStudent = Math.floor(r_stud.length * Math.random());
    var s_randomStudent = r_stud[i_randomStudent];

    if(r_rndm.indexOf(s_randomStudent) >= 0){
        //If the student has already been selected, try again.
        getStudent();
    }else{
        //Adding the student to both new and all-time selections
        r_rndm.push(s_randomStudent);
        r_newr.push(s_randomStudent);

        //Returning the updated array
        return r_newr;
    }

};

function findStudent(){

    //Reseting the new array.
    r_newr = [];
    for(i = 0; i < 3; i++){
        getStudent();
    };

    //Printing the contents of the new array to console.
    console.log(r_newr);

    for(i = 0; i < r_newr.length; i++){
        separator = (i == r_newr.length - 1 && r_rndm.length == 0 ) ? '' : ', ';
        msg8.innerHTML += r_newr[i] + separator;
    }

};

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

Is it possible to resize without defining dimensions?

Currently, I am working with Access 2010 on Win7. I have recently discovered that I can dynamically size my arrays at runtime simply by using ReDim arrayName(x) without having to declare the array with Dim arrayName() first. Sub FooBar() ReDim myArray( ...

Prevent alert box from closing automatically without clicking the ok button in ASP.NET

I'm creating a project in ASP.NET where I need to display an alert box and then redirect to another page. Below is my code: var s = Convert.ToInt32(Session["id"].ToString()); var q = (from p in db.students where p.userid == s ...

Using Blade to pass an array of arrays

I am facing an issue with passing an array of arrays from the controller to the view in Laravel. Despite conducting some research, I have not found any relevant topics to assist me with my problem. The tables involved are Shops, Items, and Items Price. Sho ...

Is there a way to ensure my function runs as soon as the page starts loading?

My goal is to have a function execute as soon as a person opens my page, without requiring any interaction. The function should trigger on page load, rather than waiting for a click event. Additionally, I want the function to repeat every 90 seconds. I&apo ...

Why is it that a specific variable is only undefined in one specific location within the entire component?

import React from 'react'; import { Formik, Form } from "formik"; import { InputField } from "./formui/InputField"; import { applyGharwapasi } from "../../appollo/applyGharwapasi/applyGharwapasi"; import { useMutatio ...

Add a variable to the configuration

Here is my configuration setup angular.module('moduleApp.config') .config(['$translateProvider', '$languageSupportProvider', function($translateProvider, $languageSupportProvider) { // Need to access data from myS ...

Shifting image from center to corner as you scroll

Hello there, I'm new to this so please bear with me for any obvious mistakes, thank you :) My goal is to have an image move from the center of the screen to the corner of the screen as you start scrolling. I've made some progress on this, but I& ...

Learn how to extract substrings from a variable within an API using Vue.js

Exploring VueJs for the first time and looking to split a string by comma (,) retrieved from an API into separate variables. The data is coming from a JSON server. "featured-property": [ { "id": "1", " ...

The inputmask is triggering an unhandled RangeError due to surpassing the maximum call stack size

I need to dynamically set a regex pattern on the idnumber field by selecting a different value from the idtype dropdown. Everything works smoothly until I choose the last option which contains a "?" character, causing the page to become unresponsive and di ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...

Utilizing ng-bootstrap within a rebranded module

I'm facing an issue with my nav-bar module that utilizes ng-bootstrap: import {NgModule, NgZone} from '@angular/core'; import { CommonModule } from '@angular/common'; import {NavigationComponent} from "./components/navigation/navi ...

The instance of my ObjectType is coming back as an empty entity

Having trouble making relationships between two object types in my code. One of them is working fine, but the other one returns an empty object and I can't seem to find the issue. The first one works as expected and logs the rank type without any pro ...

Manipulate a value using JavaScript

While the intention is for the button value to switch between 1 and 0, the echo $_POST["ordina"] consistently returns 1. Despite checking the code multiple times, I am unable to identify the issue. <script> function order() { if (document.ordination ...

Iterating through a JSON object using an API loop

Just starting out in JS and I am attempting to use a for loop to combine all the 'text' from various JSON objects into one cohesive paragraph. For example, it should read like this: "Hello, and welcome to the Minute Physics tutorial on basic Rock ...

Look for distinct values within the realm of Android

In my Pedido model, there is a RealmList of Itens, each with a produt_id. To add Itens to Pedidos, I am using the following method. However, this approach allows for duplicate items to be added to Pedidos, and I am struggling to find a way to check if an i ...

Assign a custom value to the ng-options and ensure that the first option is selected by default

Hey there, I'm currently working on the following: $scope.test = [ {"value" : 0, "text" : "00:00"}, {"value" : 900, "text" : "00:15"}, {"value" : 1800, "text" : "00:30"} ]; and in my select element, this is what I hav ...

A guide on breaking down complex mathematical expressions with arrays using javascript

I am looking to store various mathematical expressions that involve basic operations such as addition, subtraction, multiplication, division, exponents, square roots, grouping, etc., along with unique placeholders in the form of a string. const json = { ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

Issue with the submission button not triggering onclick event correctly

I've been trying to add an onclick event to a submit button. I've searched various tutorial sites and followed all the suggestions, but none of them have solved the issue. Interestingly, when I include an alert in the function being called, it wo ...

Sending an array from the front-end to the back-end in Laravel with JavaScript

I am experiencing difficulty passing a objs array to a function in a Laravel controller using ajax. Unfortunately, I am not receiving any data after the post request. <script> var itemCount = 0; var objs=[]; $(document).read ...