Selecting a unique element at random from an array in Javascript

I want the function to randomly select elements from the array without repetition

function RandomSelect() {
    let names = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"];
    let paragraph = document.getElementById("demo1");
    let text = " ";
    for (let i = 0; i < 4; i++) {  
            let selectedName = names[Math.floor(Math.random() * names.length)];
            text+= "This is " + selectedName  + "<br>";
    }
    paragraph.innerHTML = text;
}

Answer №1

If you want to remove an item from an array after displaying it, you can utilize the splice method.

To avoid modifying the original array, you can make a copy of it before making any changes.

let id = Math.floor(Math.random() * choices.length);
let p = choices[id];
choices.splice(id, 1);
text += "Selected option: " + p + "<br>";

Here is the working code snippet:

function generateOptions() {
  let choices = ["Red", "Green", "Blue", "Yellow", "Orange"];
  let displayElement = document.getElementById("optionsDisplay");
  let text = "";
  
  for (let i = 0; i < 4; i++) {
    let id = Math.floor(Math.random() * choices.length);
    let p = choices[id];
    choices.splice(id, 1);
    text += "Selected option: " + p + "<br>";
  }

  displayElement.innerHTML = text;
}
<div id="optionsDisplay"></div>
<button type="button" onclick="generateOptions()">Generate Options</button>

Answer №2

Presented below is a shuffle function that follows the Fischer-Yeats algorithm. This method involves swapping elements using a temporary variable and decrementing from the length of the array.

let names = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"];

function shuffle(array) {
  let qty = array.length, temp, i;
  while (qty) {
    i = Math.floor(Math.random() * qty--);
    temp = array[qty];
    array[qty] = array[i];
    array[i] = temp;
  }
  return array;
}

document.querySelector('output').textContent = shuffle(names);
<output></output>

Answer №3

I trust that my assistance has been beneficial

function GenerateNames() {
    let Names = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"];
    var RandomizedNames = Names.sort(() => Math.random() - 0.5); // <- Create a new array with random order
    let output = document.getElementById("output");
    let text = " ";
    for (let i = 0; i < 4; i++) {  //Names.length = 7
            text += "This is " + RandomizedNames[i]  + "<br>";
    }

    output.innerHTML = text;
}

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

Vue.js is encountering an issue with receiving the accurate return value from a POST function

I am facing an issue where I am unable to receive the full data that is being sent from the frontend to the backend. Here is an example of the data structure that I am sending: { _id: 64a8a8e9903039edb52ccc4c, productName: 'Vial 2ml(US) Type1&apos ...

How can AngularJS handle multiple views sharing the same controller and ensure that the controller is executed only once?

Currently, I am facing a situation where I have two separate views that I would like to control within a single controller. The issue is, the controller is being executed twice. Is there a way to link multiple views to the same controller without the cont ...

Struggling to upload files using multer in Node.js?

Currently attempting to implement a feature where multiple files can be uploaded using a modal that includes a form with an input field. Here is the structure of my modal (in jade template format): #modalAddFile.modal form#uploadForm(enctype='mu ...

Failing to provide a response to the API for /api/register could potentially lead to requests becoming stuck

Currently working on a registration feature in Next.js where I am implementing password hashing using bcrypt before storing it in the database. Although the functionality seems to be working fine, calling the registration API results in a warning message: ...

Check my Twitter feed every 10 seconds

I'm attempting to access my Twitter feed (sent from a smartphone) for a local application, as Twitter is remote... I created a jQuery + JSON script, but with my overly frequent setInterval at 25ms, I quickly hit the limit of 150 requests per hour and ...

How can I make an image the background on a webpage when clicking the mouse?

I find myself in a predicament without any code to guide me. The idea seems simple - I desire the ability to select an image from a collection and set it as the background image for the webpage. While I understand that JavaScript is essential for this tas ...

How can I append a string to a JSON array in Python?

Recently, I came across a data.json file { "names": [ { "firstnames": ["Jim", "Joe", "Emma"] } ] } My goal is to update the existing list of names in "firstnames". For example, ...

Is there a way to ensure that when a user updates the src attribute of a video element in a REACT Gutenberg block, the change is immediately visible to them?

I am currently in the process of developing a custom Gutenberg block for WordPress by utilizing @wordpress/create-block. As part of this project, I am incorporating the MediaUpload React component, which can be found at this link. Within the block, there ...

Exploring the wonders of Angularjs and the dynamic capabilities of streaming data

Using AngularJS's $http to request streaming data like this: $http({ method: 'POST', url: url, data: JSON.stringify(data), headers: config }).success(function(responseData) { console.log(responseData); }).error(funct ...

Using ajax for transferring form data to a different php page

Hello everyone, I'm in need of assistance. I have a form on one PHP page and I want to use AJAX to pass the data to another PHP page that will update my database and then return the results. <form name="profile" class="profile"> < ...

retrieving an element from a collection of objects

For a project utilizing the openweather api, I encountered fluctuating data based on the time of day it is viewed. My goal is to loop through the first 8 objects to identify a dt_txt value of 12:00:00. Once found, I intend to store this result in a variabl ...

What strategies can be implemented to improve this code and eliminate the issue of encountering 'time limit exceeded'?

Here is the link to the problem that I need help with optimizing the code for. I am struggling to figure out how to make this program run within 1 second without getting a TLE. Problem link: My code: #include <bits/stdc++.h> using namespace std; ...

Methods for sending data from Angular to the server and vice versa

Currently, I have an application that utilizes Express along with Jade templates. I am in the process of developing a new version of the app using Angular and client-side HTML. In order to determine user permissions within my Angular code, I require acces ...

Why isn't offsetTop working for a div within a table in HTML and Javascript?

When using the offsetTop property to get the absolute position of an object, it works fine when the objects are outside of tables. However, if the object is inside a table, it always returns 1. Why does this happen and how can it be avoided? To see an exa ...

Unable to achieve the desired focus on a specific element using JavaScript's .focus() method

After executing the command $('#someelement').focus(), I am not receiving any error message but the functionality is not working as expected. Even when I attempt to retrieve document.activeElement, it continues to return the body element. Here i ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

Checking whether one list can be equivalent to another (in terms of both value and order) after deleting some elements from the first list in

In need of assistance! I have two sets of data input labeled as 'a' and 'b'. I am currently testing to see if 'a' can be aligned with 'b' by eliminating elements from 'a'. For example, with 'a' be ...

Navigate to the subsequent field in an HTML5 form without any manual intervention

I have created the following HTML5 form: <form> <input type="text" name="orderno" /> <input name="picture" id="img" type="file" accept="image/*" capture="camera" /> <input class="btn-success" type="submit" name="submit" value="Uplo ...

I am attempting to pass information through the body of an Axios GET request to be used in a Django backend, but when I try to print the request.body

As reported by Axios, it seems that this is a feasible solution: https://github.com/axios/axios/issues/462#issuecomment-252075124 I have the code snippet below where pos_title contains a value. export function getQuery(pos_code, id) { if (id === 94) ...

What is the best way to differentiate the behavior of two identical classes using a single JavaScript function?

Can someone help me figure out how to make two circles move differently with the same JavaScript function? I'm new to JavaScript and struggling to differentiate between classes in HTML to achieve this. My goal is to have each circle move randomly and ...