Selecting arbitrary elements from an array to generate a fresh array

I am working on a project where I need to select three random values from an array and display them in a new array on my website. It is important that each value is only selected once.

Here is what I currently have:

 var students = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Line", "Pia"];
 var pick = students[Math.floor(Math.random() * students.length)];

I am considering adding an id to my HTML so that the new array can be displayed on the website, but I am uncertain about the next steps.

Answer №1

To achieve a random sorting, first shuffle the order and then select the top three items:

student
   .sort(function(){
       return Math.random() - 0.5;
     })
   .slice(0,3)

The reason for subtracting 0.5 from Math.random() is because the sort function expects positive or negative values to determine order, but Math.random() generates values between 0 and 1 by default. By subtracting 0.5, we introduce negative values which allow for proper sorting.

Answer №2

If you want to randomly select students in a loop, you can try the following approach:

var students = ["Hans","Ole","Nils","Olav","Per","Knut","Line","Pia"];
var randomStudents = [];
for(var i = 0; i < 3; i++) {
    var pick = students[Math.floor(Math.random() * students.length)];
    randomStudents.push(pick);
}

Keep in mind that this method may result in duplicate entries in the array. To prevent duplicates, you should check if the student is already included in the array before adding them.

You can achieve this using recursion.

https://www.example.com/random-student-selection

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

Why was the event handler attached and for what purpose does it serve in this particular location?

When using Typescript with JQuery, I encountered a strange issue where a click event seemed to be added multiple times each time the user opened a dialog. Despite creating a new SettingsDlog object for each dialog instance, the click event did not behave a ...

Animate play in reverse with JavaScript upon mouse exit

I'm currently using a code that works really well, but there's one thing I'd like to improve. When the mouse leaves, the animation stops abruptly which doesn't provide a great user experience. I have a few ideas: How can I make the &a ...

Optimal management using an image and an onClick event to trigger a JavaScript function

Which control stands out as the optimal choice for displaying images, executing JavaScript functions without postback, and possibly even changing images on hover? ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

Is there a way to access and read the console log of a specific website using Python code? I am looking to extract messages such as "ok" and "connected

Seeking guidance on how to interpret console log output for a specific website while automating with Python. Struggling to extract live console data through Selenium, as there's no built-in function for reading logs in real-time. Although I can acces ...

Access data in an array using a specific index in Typescript

Here is the JSON format I am working with: { "records": [ { "ID": "4", "TYPE": "landscape", "FIMAGE": "viewveni.jpg", "COUNT": "4444" } ], "pagination": { "count": 1, "page": 1, "limit": 10, "totalpages": 1 } } I'm facing a challenge trying to retri ...

Create a loop in Vue.js 3 without the need for a query

Can someone help me understand how to fetch data using a loop in Vue.js version 3 when working with queries? I am trying to retrieve an object based on its id, which is obtained from the URL. However, I seem to be facing some difficulties. Any guidance wou ...

What is the best way to retrieve a specific children element from a JSON object in JavaScript based on a keyname and value match

Recently, I encountered a JSON data structure that looked like this: var jsonData = { "id": 0, "content": "abc", "children" : [{ "id": 1, "content": "efg", "children" : [] } { "id": 2, "c ...

"Add a hover effect to fade the image and make it clickable for a

Is there a way to make the entire image a clickable link when it's hovered over, rather than just the text inside? I could use some assistance with this. Javascript: $('.thumbnail').hover(function() { $('.thumbnail img').stop ...

Elements on the page are quivering as a result of the CSS animation

When a user clicks anywhere on a div, I have added a ripple effect to give it some interaction. However, there is an issue where the element shakes and becomes blurry when the page is in full screen mode until the ripple effect disappears. Below is the Ja ...

A tailor-made Angular filter designed to exclusively show items falling within a specific date range

Hi there! I am currently delving into AngularJS and working on an application that pulls articles via JSON. My goal is to display items within a specific date range when a button is clicked. While I have the logic figured out, I am unsure of how to approac ...

Functionality of JavaScript limited within a form

Here is some HTML code I am working with: <div class = "login"> <form> <input type="text" id="username" name="username" placeholder="Username" style="text-align:center"> <br> <br> <input type="pa ...

Showing options in the navigation bar upon user authentication with Passport in NodeJS

When a user is connected, I want the navbar to display "Profile of: {USER}", otherwise it should show a set of Sign up/Login tabs. The challenge lies in using EJS with separate "head.ejs" and "header.ejs" sections placed in a /partials folder within the / ...

Utilize Autodesk Forge to adjust the DataVisualisation sprite offset and customize various THREE js sprite parameters

After going through this tutorial at , I successfully implemented a system in my Forge viewer app to add sprites on mouse click. However, I am curious if there are other parameters that can be modified besides changing spriteSize, such as the sprite ancho ...

Retrieval of jQuery remove() method

Essentially, I am utilizing an OnClick function to delete a DIV. Once the OnClick is triggered, it invokes the remove() jQuery function to eliminate the div. Below is my code that implements the removal using remove(): <div id="add"> <button typ ...

What methods can I use in JavaScript to modify input values and update them in my HTML output?

How can I retrieve the input number value in HTML, perform a mathematical formula with the value when it changes, and display the updated data on the page without reloading? This is my HTML: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3. ...

Error: Attempted to remove an item from an index beyond the array's size in Swift causing a fatal error (lldb

I'm currently working on a method to compare two arrays, 'list' and 'id'. The objective is to determine if any of the integers stored in 'id' are also present in 'list', and then remove those integers from &apos ...

Looking for assistance with PHP if statement and troubleshooting iFrame issues

Using the PHP if statement below on my website: <?php if(empty($_GET['tid'])) echo '<iframe src="http://tracking.mydomain.com/aff_goal?a=33&goal_id=47" scrolling="no" frameborder="0" width="1" height="1"></iframe>'; ...

I encountered an unexpected token error while using JavaScript syntax with objects

In my current coding project, I have encountered an issue while attempting to utilize an object from a different JavaScript file. Despite importing the necessary function from this external file, there seems to be a syntax error present. Can anyone offer ...

Cordova's Dynamic Scrolling Feature for iOS Overflowing Elements

When using the Safari iOS browser, listening to scroll events triggers the console message every time, even during momentum. However, in the Cordova built app, the message is only triggered when the scroll has stopped. el-with-webkit-overflow-scrolling-to ...