By applying this filter, you can generate N C K combinations. N is length of the array. K is number of elements to be in set of combination. User has to give K value

Markup

myArray is array
combinate is filter name
2 is K value
<div ng-repeat="val in myArray | combinate:2">{{val}}</div>

Script

iArray is the input array
kval is the K value
combinate is filter name
angular.module('myApp', []).filter('combinate', function() {
    return function(iArray, kval) {
        var n = iArray.length;
        function combine(k) {
            var result = [];
         
            //illegal case
            if (k > n) {
                return null;
            //if k==n
            } else if (k == n) {
                var temp = [];
                for (var i = 0; i < n; i++) {
                    temp.push(iArray[i]);
                }
                result.push(temp);
                return result;
            //if k==1
            } else if (k == 1) {
         
                for (var i = 0; i < n; i++) {
                    var temp = [];
                    temp.push(iArray[i]);
                    result.push(temp);
                }
         
                return result;
            }
         
            //for normal cases, initialize a list with one element
            for (var i = 0; i < n - k + 1; i++) {
                var temp = [];
                temp.push(iArray[i]);
                result.push(temp);
            }

            
            return combineHelper(k, result);
        }
         
        function combineHelper(k, result) {
            
            var prevResult = result.slice();
         
            if(result[0].length == k) return result;
         
            result = [];
            for (var j=0; j<prevResult.length; j++) {
                    var one = prevResult[j];
                for (var i = j + 1; i < n; i++) {
                    var temp = one.slice();
                    temp.push(iArray[i]);
                    result.push(temp);
                }
            }
         
            return combineHelper(k, result);
        }
        return combine(parseInt(kval));
    };
}).controller('MyController', [ '$scope', function($scope) {
    $scope.myArray = [1,2,3,4,5];
} ]);

0 comments:

Blogroll

Popular Posts