Using AngularJS how could I randomize the order of a collection?

angularjs, random, sorting

Solution

EDIT Warning!: These results are skewed, don't use this. This answer is only left as a warning until further editing.

Explanation: There should be an equal chance of any item being in the first position, but the actual percent chance after 10,000 iterations of, for example, 6 items, ends up being

1: ~28%, 2: ~10%, 3: ~14%, 4: ~20%, 5: ~12%, 6: ~15%

https://jsfiddle.net/sh0ber/km9cqvpf/

`orderBy` can take a function parameter, just like `array.sort` so you can use your HTML above and define a function `random` on the scope like:

$scope.random = function(){
    return 0.5 - Math.random();
};

This will return a random value sometimes negative, sometimes positive, sometimes 0, which will randomly sort the array.

Problem

How would you order a list of items in AngularJS in random order? I was thinking that the built-in `orderBy` filter would work but I'm not sure how without adding some additional data to the model. Something like would be great. ``` item in items | orderBy:random ``` My next thought was to create a custom filter but I'd prefer to avoid that if there is something better already available.

Original source

Related problems