Files
reference/source/_posts/note/javascript/random/get-random-items-of-an-array.md
T
2022-11-16 14:10:09 +08:00

837 B

title, tags, layout
title tags layout
How to get random items of an array in JavaScript
JavaScript
ES6
one-line
js
Random
note

In this Article we will go through how to get random items of an array only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const randomItems = (arr, count) => arr.concat().reduce((p, _, __, arr) => (p[0] < count) ? [p[0] + 1, p[1].concat(arr.splice(Math.random() * arr.length | 0, 1))] : p, [0, []])[1];

Example

randomItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3);                        // [4, 8, 5]
randomItems(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 4);     // ['e', 'c', 'h', 'j']