This filter will take array as input and generates all permutations to that array. Observe below markup

Markup

Here myArray is Javascript array, permute is filter
<div ng-repeat="val in myArray | permute">{{val}}</div>

AngularJS Code

This permute filter generates all permutations of given array and gives them as output
angular.module('myApp', []).filter('permute', function() {
    return function(num) {
        var result = [];
        //start from an empty list
        result.push([]);

        for (var i = 0; i < num.length; i++) {
            //list of list in current iteration of the array num
            var current = [];

            for (var k = 0; k < result.length; k++) {
                var l = result[k];
                // # of locations to insert is largest index + 1
                for (var j = 0; j < l.length + 1; j++) {
                    // + add num[i] to different locations
                    l.splice(j, 0, num[i]);

                    var temp = JSON.parse(JSON.stringify(l));
                    current.push(temp);

                    // - remove num[i] add
                    l.splice(j, 1);
                }
            }

            result = JSON.parse(JSON.stringify(current));
        }
        return result;
    };
}).controller('MyController', [ '$scope', function($scope) {
    $scope.myArray = [1,2,3,4,5];
} ]);

0 comments:

Blogroll

Follow this blog by Email

Popular Posts