4

I know how do this in PHP, but in javascript arrays are weird.

So I have a set of image transitions which have effects that use easing equations. For certain effects I want to pick up a random value from a array of multiple values:

something like:

easing: randomFrom(array('easeOutElastic', 'easeOutBounce', 'easeOutSince')),

0

4 Answers 4

11
function randomFrom(array) {
  return array[Math.floor(Math.random() * array.length)];
}

// in your code
easing: randomFrom(['easeOutElastic', 'easeOutBounce', 'easeOutSince']),
Sign up to request clarification or add additional context in comments.

2 Comments

I was sooo close, but you forgot to return :-P
@Neal, oops, that's what happens when you do too much Ruby.
5

Try this:

function randomFrom(arr){
    var randomIndex = Math.floor(Math.random() * arr.length);
    return arr[randomIndex];
}

Comments

1

For a demo I was trying to get a random easing string ;)

function getRandomEasing() {
   var easingArr = [];
   for(easing in $.easing){
      easingArr.push(easing);
   }
   var rnd = Math.floor(Math.random() * easingArr.length);
   return easingArr[rnd];
}

var randomEasing = getRandomEasing();

Fun demo: http://jsfiddle.net/aamir/psWvy/

1 Comment

I don't understand why in the original solution, you need to create a new array every time? Why not just directly return an element inside of $.easing? jsfiddle.net/psWvy/2
1

I am a late comer to this question. If you don't mind adding a method to Array, you can:

Array.prototype.pickARandomElement = function() { 
     return this[Math.floor(Math.random() * this.length)]; 
}

test run:

> [10, 123, 777].pickARandomElement()
10

> [10, 123, 777].pickARandomElement()
777

> [10, 123, 777].pickARandomElement()
777

> [10, 123, 777].pickARandomElement()
123

The following is just for fun:

Array.prototype.pickARandomElement = function() { 
    return this.sort(function() { return Math.random() - 0.5; })[0]; 
}

it is like shuffling a deck of cards and returning the top card. But its time complexity is O(n log n) so I wouldn't really use it, and it is just for fun. The first solution here is a solution with O(1).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.