DEV Community

Consecutively return a random item from a JavaScript array

Alex Carpenter on March 11, 2019

View this post on alexcarpenter.me The other week I was working on a side project where I needed to consecutively return a random item from an arr...
Collapse
 
eostrom profile image
Erik Ostrom

Another way to do it is to create an array that contains every item except the current one, and then take a random item from that:

btn.addEventListener('click', function() {
  var otherFruits = fruit.filter(function(item) { return item !== currentItem });
  currentItem = randomItem(otherFruits);
  console.log(currentItem);
}, false);
Collapse
 
hybrid_alex profile image
Alex Carpenter

Definitely, but it seemed more performant to not create a new array using filter on every click.

Collapse
 
eostrom profile image
Erik Ostrom

It's hard to know, right? I would guess the average performance for my version is worse, for the reason you mentioned. But the worst-case performance for your version is worse, because in theory that loop can spin and spin until the random number generator picks a different fruit.

But really, the performance costs we're talking about aren't important, if they only happen once per human click interval. I'd favor readability... if I could just decide which one was more readable.

Thread Thread
 
eostrom profile image
Erik Ostrom

... Anyway, I just think it's fun to see multiple ways to do things.