Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random and remove from collection using underscore

I've got a collection of 20 results (objects), and what I'd like to do when a button is clicked is to:

a) Pick a random object from this collection/array

b) When the button is pressed again - I don't want that object re-picked until the collection is exhausted (i.e. until the 20 items are shown)

I thought of just splicing out the index of that collection, but I'm hoping for a cleaner way using Underscore.js

EXAMPLE:

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11...]

var getRand = _.random(0, data.length);

==> 3

Next time I press the button, I don't want the result "3" to re-appear as it's been used

I hope this makes sense

like image 732
Pete Avatar asked Sep 04 '26 14:09

Pete


2 Answers

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

// cache indexes
var cache = _.map(new Array(data.length + 1).join(), function (item, index) {
  return index;
});

// get random from cached array
var rand = _.random(0, cache.length);

// remove random index from cache
cache.splice(rand, 1);

console.log(rand, cache)
like image 56
Vitalii Petrychuk Avatar answered Sep 06 '26 05:09

Vitalii Petrychuk


var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var picked = [];

$("#link").click(function() {
   if(data.length == 0) return;
   var pick = data.splice(_.random(0,data.length),1);
   picked.push(pick);
   $("#pick").html(pick);
   $("#data").html(data.join(","));
   $("#picked").html(picked.join(","));
});

http://jsfiddle.net/Z3vjk/

like image 26
Scott Puleo Avatar answered Sep 06 '26 05:09

Scott Puleo