This page looks best with JavaScript enabled

Get a random value from array

 ·   ·  ☕ 1 min read

Get a random unique value from a specified array.

You can use one of the hundred ways to get values at a specific index, or iterate over an array and get values in sequence.

1
2
3
4
5
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(nums[0]); // 1
nums.forEach(val => console.log(val));
// 1 2 3 4 5 6 7 8 9

But, what if you want to randomly get values from the array?
That is easy too.

1
2
3
console.log(nums[Math.floor(Math.random() * nums.length)]);
console.log(nums[Math.floor(Math.random() * nums.length)]);
console.log(nums[Math.floor(Math.random() * nums.length)]);

However, you will see more repeating values than expected in the above logic (especially if you have a small array). To avoid repetitions, you can compare your current random index with previous random index, and change it if equal.

You may find such a logic useful when generating test data for a field that allows a specific set of values (e.g. City, Status etc.)

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things