[Home] >  Random >  Get a random item and remove it from an array

Get a random item and remove it from an array

JavaScript version

const randomItem = (arr) => arr.splice((Math.random() * arr.length) | 0, 1);

TypeScript version

const randomItem = <T,>(arr: T[]): T => arr.splice((Math.random() * arr.length) | 0, 1) as unknown as T;

Examples

const arr = [1, 3, 5, 7, 9];
randomItem(arr); // 7
// arr = [1, 3, 5, 9]