How to get random elements from an array [duplicate]

You could shuffle the array and pick the first four.

numbers.sort( function() { return 0.5 - Math.random() } );

Now numbers[0], numbers[1]… and so on have random and unique elements.

Note that this method may not be an optimal way to shuffle an array: see Is it correct to use JavaScript Array.sort() method for shuffling? for discussion.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)