随机唯一数字的大小数组 [英] Sized array of random unique numbers

查看:52
本文介绍了随机唯一数字的大小数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道最简单的方法是获取具有一定大小,唯一随机数的数组.

I was wondering what was the most concise way to get an array of a certain size, of unique random numbers.

我得到这样的随机数:

times(4, () => random(30, 95));

但这不是唯一的.我可以用uniq进行过滤,但是我需要保证数组长度为4.我想用lodash的方式来做.有什么想法吗?

However this is not unique. I can filter this with uniq but I need to gurantee length of 4 of array. And I want to do it the lodash way. Any ideas?

推荐答案

很容易...

const uniqRandomNumbers  = _.sampleSize(_.range(30, 95), 4);
console.log(uniqRandomNumbers);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

这篇关于随机唯一数字的大小数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆