Sorting
http://angularjs.org/
by anup1986
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://underscorejs.org/underscore.js"></script>
<div class="container" ng-controller="myCtrl">
<div class="row">
<div class="col-xs-12">
<div class="col-xs-1">
<div ng-repeat="n in list track by $index">{{n}}
<br/>
</div>
</div>
<div class="col-xs-1">
<div ng-repeat="n in shuffled track by $index">{{n}}
<br/>
</div>
</div>
<div class="col-xs-1">
<div ng-repeat="n in rev2 track by $index">{{n}}
<br/>
</div>
</div>
</div>
</div>
</div>
CSS
body {
margin-top: 50px;
}
/*
First, we'll sort and group the related array elements together:
v = arr.sort.group_by { |e| e }.values
# => [[38, 38], [40, 40, 40], [41, 41, 41, 41], [60]]
Let's make a new array for the result:
r = []
Now we'll get the one with the largest number of elements:
max = arr.map { |e| arr.count(e) }.max
Then we'll loop through the array that many times,
max.times { ... }
pulling one element from each subarray each time, then putting it onto the result array:
max.times { v.each { |a| r << a.shift } }; r.compact!
and we have our answer:
# => [38, 40, 41, 60, 38, 40, 41, 40, 41, 41]
*/
JavaScript
console.clear();
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', [
'$scope', function ($scope) {
$scope.list = [1, 1, 3, 3, 3, 4, 6, 4];
$scope.shuffled = [];
$scope.groups = _.sortBy(_.groupBy($scope.list, function (x) {
return x;
}));
var max = _.max($scope.groups, 'length');
_.each(max, function (x) {
_.each($scope.groups, function (g) {
if (g[0]) {
$scope.shuffled.push(g.shift());
}
});
});
}]);