M
M
Muranx2020-04-19 08:42:22
JavaScript
Muranx, 2020-04-19 08:42:22

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]

! ! ! I wrote the implementation of this function, BUT it has a minus, which I strongly ask you to consider
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);

The fact is that this function in the 1st OUT can return a smaller number, and in the 2nd, it each time considers the elements of the array from the 0th index, and the chance that the resultelements 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

1 answer(s)
I
Ivan Klimenko, 2020-04-19
@Muranx

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 question

Ask a Question

731 491 924 answers to any question