Using JavaScript to select numbers at random from a predefined set to ensure that each number is chosen uniquely

Given an array arr[8,4,2,1,7,5,3,0] containing 8 elements, I am looking for a way to randomly select each number from the array without any repeats. The goal is to ensure that every number is picked exactly once.

Answer №1

This code can be simplified by using a basic while loop:

const numbers=[8,4,2,1,7,5,3,0];

while(numbers.length>0) {
  let index = Math.floor(Math.random() * Math.floor(numbers.length));
  console.log(`Selected number: ${numbers[index]}`);
  numbers.splice(index,1);
};

Example output:

// "Selected number: 4"
// "Selected number: 7"
// "Selected number: 0"
// "Selected number: 2"
// "Selected number: 1"
// "Selected number: 3"
// "Selected number: 8"
// "Selected number: 5"

Codepen: http://jsbin.com/bukoqujupo/edit?js,console

This code snippet essentially loops through the array, randomly selecting and displaying elements until all are picked. It repeats this process as long as there are elements in the array.

Answer №2

Here is a potential solution...

let numArray = [8,4,2,1,7,5,3,0];
let shuffleArray = (arr) => {
    for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
};

console.log(shuffleArray(numArray))

Answer №3

Is this what you had in mind?

function generateRandomNumber(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

let numbers = [8, 4, 2, 1, 7, 5, 3, 0],
  selectedNumbers = [];

function pickRandomNumber() {
  let randomIndex = Math.floor(Math.random() * Math.floor(numbers.length));
  if (selectedNumbers.indexOf(randomIndex) !== -1) {
    return pickRandomNumber()
  }
  selectedNumbers.push(randomIndex);
  return numbers[randomIndex]
}
numbers.forEach(() => {
  console.log(pickRandomNumber());
})

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

Tips on creating a keypress function for a div element with the contenteditable attribute

Hey there, I have managed to create a textarea within a div by using -webkit-appearance. However, I am currently struggling to add an event to this div on key press. I have been trying my best to figure it out but seem to be missing something. If you coul ...

Display a text field upon clicking on a specific link

I am trying to create a text field that appears when a link is clicked, but I haven't been able to get it right yet. Here is what I have attempted: <span id="location_field_index"> <a href="javascript:void(0)" onclick="innerHTML=\"< ...

NodeJS script for mass downloading videos

I'm looking to create a NodeJS script that can download videos from a CSV list. I've successfully managed to download images through HTTP, but I'm struggling to find a solution for downloading video files and handling HTTPS URLs. Any advice ...

Perform an operation in JQuery after a different operation has been completed

Recently, I came across this JavaScript function that displays a loading image for a few seconds before revealing a hidden div: <script type="text/javascript> $(document).ready(function () { $('#load').html('<img style="display ...

Tips on sending information to a different page through jQuery's AJAX functionality

I'm facing an issue with an ajax call. Below is my code for the ajax: $('#Subjects').click(function() { $.ajax({ type: 'POST', url: '../portal/curriculum.php', data: 'studentNumber=&apos ...

seamless blending effect as the opacity transitions smoothly on an element with a applied filter

I've been working with a DIV that has a blur filter applied to it, and I'm attempting to smoothly "fade in" the DIV using CSS opacity (going from 0 to 1) with a one-second transition. However, even though the DIV does fade in, it's quite gli ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

Ways to minimize the occurrence of duplicate values in a table

In the application, I have a table where I add multiple values to an Array. These arrays display the values in the table columns, sometimes resulting in duplicate values. Below is a small example to illustrate the issue. What is the best way to eliminate ...

Get multiple increment buttons functioning

I've managed to create an increment counter that updates the value in a .txt file on my server every time I click a button by +1. It's working flawlessly and here's how it looks like: <!DOCTYPE html> <html> <head> <meta ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

Tips for utilizing jQuery to identify an image that is being hovered on?

Concept My goal is to create an effect where a user hovers over an image and a transparent overlay div appears on top of it. This overlay div starts with a height of 0px and should increase to half of the image height upon hover. The hover functionality ...

Displaying local time alongside global time using PHP

I have a challenge - I am storing time in DATETIME format and now I need to display it in the local timezone. Does anyone know how to achieve this using PHP? ...

Find a way to sift through an array of objects to ensure that each object is distinct from the others

Here is an array where objects with the same values for st and ct should be considered identical. For example, the first and third objects have the same values for st and ct, so the third object should be filtered out of the final array. How can I achiev ...

What is the best way to automate the testing of functions with click handlers that contain async await statements using the karma-jasmine framework?

Trying to test my button that runs a function asynchronously. Here is the logic for my button: // Function below will run when user clicks the button this._pageModule.favoriteButtonCallback = async () => { try { await this._favorit ...

Retrieve information from a template and pass it to a Vue component instance

Being a newcomer to vue, I have a fundamental question. In my template, I have a value coming from a parsed object prop like this: <h1>{{myval.theme}}</h1> The above code displays the value in the browser. However, I want to store this value i ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

Arrange the array depending on the existence of properties in the objects

Is there a way to efficiently organize an array like the following in cases where certain fields are missing? For instance, consider the current array: const users = [ { id: 1, firstname: 'Jerry' }, { id: 2, firstname: & ...

Is it possible to access dl, dt, or dd tags based on their roles within the testing library?

Is there a way to use the testing library to specifically target the dd tag based on its role? <dl> <dt>ID</dt> <dd>123456</dd> </dl> I attempted: screen.getByRole('term', { name: 'ID' }) as wel ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...