The optimal solution
The only change you need to make to your existing code, is replacing ...
$(this).css('color', colors[Math.floor(Math.random() * colors.length)]);
... with ...
$(this).css('color', colors.splice(Math.floor(Math.random() * colors.length), 1));
How it works
The most efficient way to get unique colors, is to use the splice()
method in combination with Math.floor(Math.random() * colors.length)
:
- The
splice()
method allows you to both (1) remove a single element from the colors
array at a position you choose, and (2) return that element.
Math.floor(Math.random() * colors.length)
allows you to make that position a random position.
Because it only takes a single for
-loop and a single splice operation per iteration, this approach is much more efficient than Praveen's approach (where you first do a shuffle and then "pop" an element from the shuffled array).
An additional advantage, is that it requires very little code.
A demo
$('a').on('click', function(e) {
e.preventDefault();
var colors = ['#0071bc', '#ff00ff', '#fcee21', '#39B54A', '#00A99D', '#662D91'];
var index, value;
$('li').each(function() {
$(this).css('color', colors.splice(Math.floor(Math.random() * colors.length), 1));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
</ul>
<a href="#">Change color</a>
(see also this Fiddle)