How to randomly select a random number of elements in an array

I want to randomly select a random number of inputs in an array of input elements.
If I use the method below, I can get one random item

jQuery.jQueryRandom = 0; jQuery.extend(jQuery.expr[":"], { random: function(a, i, m, r) { if (i == 0) { jQuery.jQueryRandom = Math.floor(Math.random() * r.length); }; return i == jQuery.jQueryRandom; } }); $("input:random").prop('id') 

But I want a random number i = of elements to be randomly selected in the array.

+4
source share
3 answers

You can use jQuery .filter() method with function:

 $('div').filter(function(){ return (Math.round(Math.random()) == 1); }).css({background: 'red'}); 

JsFiddle example

+7
source

You are currently checking if the index is equal to a random number. It might be better to create a random number for each input and check if it is more than 1 or less. So randomize the number between 0 and 2. something like:

 jQuery.extend(jQuery.expr[":"], { random: function(a, i, m, r) { return Math.random() > 0.5; } }); alert( $("input:random").length ); 

In addition, if you get a support from an element, he will receive it only from the first.

+4
source

I suggest a non-jQuery answer to the question of how to accidentally get count elements from an arr array

 var pickRandom = function (arr, count) { var out = [], i, pick, clone = arr.slice(0, arr.length); for (i = 0; i < count; i ++) { pick = Math.floor(Math.random() * clone.length); if (clone[pick] !== undefined) { out.push(clone[pick]); clone.splice(pick, 1); } } return out; }; 

This function ensures that the original array is preserved and correctly processes undefined values.

+1
source

Source: https://habr.com/ru/post/1383586/


All Articles