From e86c1eaf3a1123e510a4d3c096c2f4c4097f6549 Mon Sep 17 00:00:00 2001 From: Arjun Mahishi Date: Fri, 15 Dec 2017 13:45:12 +0530 Subject: [PATCH] Added snippet to sample an array --- snippets/array-sample.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snippets/array-sample.md diff --git a/snippets/array-sample.md b/snippets/array-sample.md new file mode 100644 index 000000000..d48f13840 --- /dev/null +++ b/snippets/array-sample.md @@ -0,0 +1,9 @@ +### Array sample + +Use `Math.random()` to generate a random number, multiply it with `Array.length` and round it of to the nearest whole number using `Math.floor()`. Works with strings too. + +```js +const sample = arr => arr[Math.floor(Math.random() * arr.length)]; + +// sample([3, 7, 9, 11]) -> 9 +``` \ No newline at end of file