get a sample of 5 elements from an array in javascript

To get a sample of 5 random elements from an array in JavaScript, you can use the following code:

index.tsx
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const sample = array.sort(() => 0.5 - Math.random()).slice(0, 5);

console.log(sample);
136 chars
6 lines

The sort() method without any arguments is used here to shuffle the array randomly. Then the slice() method is used to select the first 5 elements from the shuffled array. Finally, the resulting sample is logged to the console.

gistlibby LogSnag