How to get random item from an array in TypeScript

1 Answer

0 votes
function getRandomItem(arr: any[]) : any{
    const index = Math.floor(Math.random() * arr.length);

    return arr[index];
}

const array = [1, 2, 5, 9, "a", "b", "c", "d"];

const result = getRandomItem(array);

console.log(result);

 
 
     
     
/*
run:
     
"c"
     
*/

 



answered Jan 25, 2022 by avibootz
...