Find a random item in an Array JavaScript Code Example

Last Updated On Thursday 20th Jan 2022
	const arr = ['one', 'two', 'three', 'four', 'five'];

Step 1: Need to find the length of an array

	const length = arr.length;  //  5

Step 2 : Create a random Number between 0 and 1 with Math.random()

	const randomNumber = Math.random();

Step 3: Multiply this random number by the length of an array to find the possible length

	const possibleLength = length * randNumber;

Step 4: Round this possible Length by Math. floor.

	const rounded = Math.floor(possibleLength);

Step 5: Return the rounded in array to the generated random integer


In Simple

	const findRandom = arr[Math.floor(Math.random() * arr.length)];