Answer the question
In order to leave comments, you need to log in
How to make a function that selects random elements of an array?
Hello! It would seem trivial, but I can’t figure out how to make a function that will take as a parameter the number of returned elements, and the array from which we will isolate them (sorry)!
let arr = [ 1, 2, 3, 4, 5, 6, 7 ];
function getRandom( n, array ) { // n - число рандомных элементов, из массива array
// . . . код который позволит получить определённое количество элементов из массива array
};
getRandom( 3, arr ); // должно получиться например [4, 6, 7] или [1, 4, 6]
let arr = [1,2,3,4,5,6,7,8,9,10];
function getRandomRiver(n, a){
let result = [];
for(let k=0; k<a.length; k++){
if(!Math.round(Math.random())) result.push(a[k]); // Math.round(Math.random()) возвращает либо 0 либо 1, если 0 то мы добавляем этот элемент в массив
if(result.length>=n) break;
};
console.log(result);
};
getRandomRiver(3, arr);
result
elements will fall into the variable closer to the end of the array is very small, but I need to was a full-fledged random covering the entire array! Thanks in advance!
Answer the question
In order to leave comments, you need to log in
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function getRandomRiver(n, arr) {
const indexes = new Set();
const limit = arr.length;
n = Math.min(n, limit);
while (indexes.size < n) {
const index = Math.floor(limit * Math.random());
indexes.add(index);
}
const result = [...indexes].map(index => arr[index]);
return result;
};
const randomSet = getRandomRiver(3, arr);
console.log(randomSet);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question