Code snippet for randomly selecting an array element in Javascript is malfunctioning

function chooseLunchBuyer(name) {
  var position = name.length;

  var randomPerson = Math.floor(Math.random() * position);

  console.log(name[randomPerson] + " is the lucky lunch buyer today.");
}


chooseLunchBuyer("Jack", "Ben", "Jenny", "Michael", "Chloe");

After running this piece of code, it's interesting to see that instead of picking a full name, it randomly selects a single letter from the first name (in this case: Jack).

Answer №1

To efficiently handle multiple arguments, consider using rest parameters to gather them in an array and then select a random item:

function chooseRandom(...options) {
  const randomOption = options[Math.floor(Math.random() * options.length)];
  console.log(randomOption + " is the chosen one.");
}


chooseRandom("Apple", "Banana", "Orange", "Grape", "Pineapple");

Alternatively, you can pass an array as a single argument instead of individual ones:

function chooseRandom(options) {
  const randomOption = options[Math.floor(Math.random() * options.length)];
  console.log(randomOption + " is the chosen one.");
}


chooseRandom(["Apple", "Banana", "Orange", "Grape", "Pineapple"]);

Answer №2

It appears that you are passing strings as individual arguments. Consider passing them as an array instead by using the function

whosPaying(["Jack", "Ben", "Jenny", "Michael", "Chloe"]);

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

Demonstration of utilizing browserify with Node.js, Express, and EJS

Struggling with browserify implementation on my web app. I ran browserify in the terminal to generate the bundle.js file. Placed it in the public/javascripts directory and included it in my EJS file, but encountering issues: Terminal input: browserify p ...

What is the best way to postpone the rendering of a table?

My table is bogged down by an excessive number of rows, causing a sluggish rendering process. I'm curious about the best method to address this issue. Are there any existing libraries specifically designed for this purpose? ...

What is the best way to terminate a MongoDB client connection in the event of an error?

I am currently managing a configuration where I have set up a MongoDB instance and operating two JavaScript services on a Linux server. One of the services, moscaService.js, is responsible for listening to MQTT topics on the server and storing the incoming ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

React frontend GraphQL client unable to properly subscribe

I recently integrated a websocket into my React app and successfully handled the back-end portion with nodejs, utilizing GraphQL playground. However, I'm facing issues with getting subscriptions to work on the client side. Despite following the docum ...

Understanding the Document.ready function?

Recently, I came across some websites that follow this specific pattern: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(function (){...do some stuff with p ...

What is the best way to pass a URL in Vue.js methods and activate it on @click event?

Currently, I am working on a Laravel Vue.js project where I am trying to implement a method to redirect to a link upon clicking a div element. The code snippet provided below showcases my approach. When the user clicks on the div, I want them to be direc ...

Enhancing presentation with a multitude of pictures

I am currently in the process of developing a slideshow feature that includes an extensive collection of images for users to navigate through using 'next' and 'previous' buttons. At the moment, each time a user clicks on the navigation ...

Trouble with Mongoose's findByIdAndUpdate function persisting even with {new: true} parameter added

I attempted to modify and update the information, but encountered an issue with mongoose findByIdAndUpdate. Even though {new: true} is included, it continues to display the original data. The database does not reflect any updates as well. The console outpu ...

Is there a way to determine if the tab has been muted by the

Chrome enables users to easily mute tabs by right-clicking on them and selecting Mute Tab. I am curious about whether there is a method to detect when a user has muted the tab. In other words, I am interested in knowing if it's possible for a website ...

How can we use the useState hook in React to dynamically generate state variables?

I'm currently working on a React app where input fields need to be stored in the state. While I can use the useState hook to easily store these values, the challenge I'm facing is that I don't know what fields are needed since they are retri ...

How can I eliminate duplicated and successive lines from a char array in the C programming language?

I need assistance with creating a function. The function, deleteIdents(), is meant to eliminate duplicate consecutive lines in a character array, while retaining one of the duplicates. It is not necessary to compare the entire line. Only the first 79 cha ...

Ways to identify when all images have been loaded during a dynamic page load

I am trying to load a page with images into a div element. I need to find out when all the images on that dynamically added page have finished loading. $("#main").load('imagespage.php', function(){ alert("Page loaded"); }); The problem is that ...

What is the process for instructing React Query fetchQuery to initiate a fresh GET request instead of relying on the cached response?

Currently, I have a function in place that initiates a GET request for my user data and stores it in the cache using react query's fetchQuery. This allows subsequent calls to simply retrieve the data from the cache instead of making a new GET request. ...

Attempting to adjust numerical values to display with precise two decimal places using jQuery

Possible Redundancy: JavaScript: how to format a number with only two decimal places I'm getting confused while using variables and now I can't seem to get the calculation working correctly. Any ideas? $("#discount").change(function(){ ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

Crafting intricate designs using AngularJS

Currently, I am developing a web application utilizing AngularJS + SpringMVC. Due to restrictions in using only pure HTML view pages, server-side frameworks like Tiles are not viable options for me. I suspect that the angularJS ng-view tag may not be robu ...

Should you construct a fresh element using JavaScript, or opt to reveal a concealed one using CSS?

What are the benefits of using the following approach: var target = document.getElementById( "target" ); var newElement = document.createElement( "div" ); $( target ).after( newElement ); compared to just hiding the newElement div with CSS and showing ...

guide on extracting values from several selectboxes and transferring them into an array

I am currently using a multi-select box that requires the ability to add and remove values, creating a comma-separated string array. To demonstrate my issue, I have created a Plunker: Plunker var msaskArray = []; $scope.$watch("MSASK", function (new ...

What is the best way to create a Laravel object for use in JavaScript in a Laravel Blade?

please add description hereI am looking to obtain an object with this particular style var zoz2= { "11-30--0001": "<a href=\"https:\/\/www.dooz.ps\/p\/107229\" >\u0625\u0637\u0644\u0627& ...