I have an array containing some items, let's say numbers:
[23,4,67,8,29,46,7,2,98]
How it is possibile to choose N different random number (no more, no less) from the array?
Behaviour expected: if N=3
[4,23,98] accepted
[7,67,29] accepted
[7,67,7] not accepted
EDIT: Finally I've found a pretty good solution. The thread as been closed so I'm publishing my solution here just for people passing by. I had an array long M and N numbers to choose so I made an array containing M numbers (indexesArray) applied the Fisher Yates algorithm to shuffle number corresponding this way to indexes of my initial array and took the first M items from that. Thanks to @ArneHugo for pointing the right path to follow.
var arrayContainingNumbersToChoose=[23,4,67,8,29,46,7,2,98];
var indexesArray=[];
var N=5;
var resultArray=[];
var M=arrayContainingNumbersToChoose.length;
for (let i = 0; i < M; i++) {
indexesArray.push(i);
} // result like [0, 1, 2, 3, 4, 5, 6, 7, 8]
indexesArray=fisherYatesShuffle(indexesArray); // result like [2, 4, 7, 6, 0, 1, 3, 8, 5]
for (let i = 0; i < N; i++) {
resultArray.push(arrayContainingNumbersToChoose[indexesArray[i]]);
}
console.log(resultArray);
function fisherYatesShuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}