How to get random item from an array in Node.js

1 Answer

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

    return arr[index];
}

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

const result = getRandomItem(array);

console.log(result);

 
 
     
     
/*
run:
     
b
     
*/

 



answered Jan 25, 2022 by avibootz

Related questions

1 answer 125 views
1 answer 128 views
3 answers 177 views
1 answer 128 views
1 answer 111 views
1 answer 125 views
...