I have the array with symbols A-E I need to output each symbol in ng-repeat, but array should be in random order and each symbol should be displayed n times (for example 4 times)
Asked
Active
Viewed 315 times
0
-
Please provide some code showing what you've tried so far. – lintmouse Jul 13 '16 at 16:27
-
$scope.symbols = [a, b, c, d, e]; I need to output this array for example like this [a, b, c, d, b, e, c, d, e, a, a, b, c, d, b, e, c, d, e, a] Each symbol must be shown 4 times, and all symbols must be shown randomly. – MikeDiam Jul 13 '16 at 16:36
-
Randomly pick the next index to splice into. – Amy Blankenship Jul 13 '16 at 16:44
-
1Create array containing each symbols `BASE = [a...e]`, create new array add N times all elements of BASE to that copy. Shuffle the last array and return it to ng-repeat. How to shuffle: http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript – csharpfolk Jul 13 '16 at 16:51
3 Answers
1
You can use the Array.prototype.sort() method to shuffle your array.
I created a function that you can pass as parameters the initial array and the times that you want to sort it, as below:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope) {
function randomize(array, times) {
var temp = [];
for (var i = 0; i < times; i++) {
array.sort(function() {
return .5 - Math.random();
});
temp = temp.concat(array);
}
return temp;
}
$scope.symbols = randomize(['a', 'b', 'c', 'd', 'e'], 4);
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
Words:
<div ng-repeat="symbol in symbols track by $index" ng-bind="symbol">
</div>
</body>
</html>

developer033
- 24,267
- 8
- 82
- 108
0
You ll probably need two functions, one to shuffle the symbols and other to set a array 'N' times with shuffling.
To Set it :
var num = 5; // 'N' time shuffling.
function setArray() {
for(var i = 0; i < num; i++) {
$scope.symbols = $scope.symbols.concat(shuffle());
}
}
setArray();
here shuffle()
is another function to select a random order of the symbols.
See DEMO here.

Sajal
- 4,359
- 1
- 19
- 39
0
OK, since the other suggestions were just so complicated, I'll build out from my comment.
var result = [];
for (var i=0; i<4; i++) {
for (var j=0; j<yourArray.length; j++) {
var newIndex = Math.floor(Math.random() * result.length);
result[newIndex] = yourArray[i];
}
}
You could probably even make a filter from this.

Amy Blankenship
- 6,485
- 2
- 22
- 45