从数组中获取两个随机的非连续且唯一的元素 [英] Getting two random non consecutive and unique elements from an array
问题描述
我正在尝试从一个不连续的列表中获取两个唯一的随机元素.数组形成如下
Hi I am trying of getting two unique random elements from a list that are not consecutive. The array is formed as following
[
{"id": 1, "name": "Monday", "workers": []},
{"id": 2, "name": "Tuesday", "workers": []},
{"id": 3, "name": "Wednesday", "workers": []},
{"id": 4, "name": "Thursday", "workers": []},
{"id": 5, "name": "Friday", "workers": []},
]
我设法获得了两个独特的元素,如下所示:
And I managed to get two unique elements as following :
getTwoNonConsecutiveDays = () => {
var days = require('./weeks.json');
let selected = [];
let randomday = () => {
const shuffled = days.sort(() => 0.5 - Math.random());
// Get sub-array of first n elements after shuffled
selected = shuffled.slice(0, 2);
但是,当我试图将条件设为不连续时,这是行不通的
However when I am trying to put condition not to be consecutive is not working
if (selected[0].id === selected[1].id) {
console.log('greseala')}
selected[0].id
推荐答案
您可以这样处理:
var days = require('./weeks.json');
function randomIndex(array){
return Math.floor(Math.random() * array.length);
}
function randomPair(array){
var index1 = randomIndex(array), index2;
do{
index2 = randomIndex(array);
}while(Math.abs(index1 - index2) < 2);
return [array[index1], array[index2]];
}
console.log(randomPair(days));
注意:虽然@Yevgen Gorbunkov在评论中说,虽然循环和退出条件不适用于小型阵列.可以添加其他if条件来检查数组的长度.
Note: While loop and exit condition are inappropriate for small arrays, as @Yevgen Gorbunkov said in comment. An additional if condition can be added for checking the length of the array.
更新:在根据@Andreas注释更新条件时,请使用Math.abs而不是多次检查.
Update: While condition update based on @Andreas comment, use of Math.abs instead of multiple checks.
这篇关于从数组中获取两个随机的非连续且唯一的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!