12-Sep-2022
.
Admin
Hi dev,
Hello all! In this article, we will talk about how to get a random item from node js in the array. This tutorial will give you a simple example of get a random item from node js. if you have a question about an array get a random item from node js then I will give a simple example with a solution. I would like to share with you find the random item from node js.
In this example how to get a random item from node js in the array. This example is used to get random array using a random function, Math. random and Math.floor() function array list.
let's see below simple example with output:
Install Node JS
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
You can multiply the random number by the number of items in the array.
index.js
// create array list
myArray = ['Great', 'Hello', 'Hi']
// get random array string
array = myArray[
Math.floor(Math.random() * myArray.length)
]
console.log(`${array} Piyush`)
You’re receiving a different greeting every time you’re running this example.
Now run app open your terminal this command line:
node index.js
Output:
Hello Piyush
It will help you...
#Node JS