Reputation:
I've got two arrays, numbers
and picks
. numbers
contains a series of numbers, and picks
is currently empty. I want to pull N values out of numbers
, and put them in picks
. So I've tried picks.push(numbers.splice(idx,1));
, where idx
is a random number between 0 and the highest index in numbers
. This doesn't seem to be working. Any advice would be appreciated.
Upvotes: 2
Views: 1276
Reputation: 106385
Well, as many others said, Array.splice() returns an array (with the elements ordered to remove from the source array). So you can either use the fact that you always take a single number from it, as in @JoeEnos answer, or employ more universal form:
[].push.apply(picks, number.splice(idx, 1));
// replace 1 with any other positive number, and it still works
Still, it looks to me you're just trying to reimplement Fisher-Yates shuffle algorithm. Here, the key is using not splice
(as reordering huge arrays might cause a performance hit), but exchange the chosen element with the one at the end of the source array. Here's how it can be done:
var source = [1,2,3,4,5,6,7,8];
var shuffled = Array(source.length);
var i, j, len;
for (i = 0, len = shuffled.length; i < len; ++i) {
j = Math.random() * (i + 1)|0;
if (i !== j) {
shuffled[i] = shuffled[j];
}
shuffled[j] = source[i];
}
console.log(shuffled);
Here's eval.in demo to play with.
Upvotes: 2
Reputation: 40403
Since splice
returns an array, you only need a small tweak, to retrieve the first (and only) item in this new array:
picks.push(numbers.splice(idx,1)[0]);
Upvotes: 3