Afimidas Afimidas - 9 months ago 31
AngularJS Question

AngularJS how to filter an element in an array

I have this massive

$scope.arrVaritions = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]
];


How can I find an element index in this array? I'm use this code, but it does not work:

$scope.elementId = 1;
$filter('filter')($scope.arrVaritions, { $scope.elementId });

lin lin
Answer Source

Try filter it in the right way like in this demo fiddle:

View

<div ng-controller="MyCtrl">
  {{filtered}}
</div>

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope, $filter) {
    $scope.arrVaritions = [
        [1, 2, 3], 
        [4, 5, 6], 
        [7, 8, 9], 
        [1, 4, 7], 
        [2, 5, 8], 
        [3, 6, 9], 
        [1, 5, 9], 
        [3, 5, 7]
    ];

    $scope.elementId = 1;
    $scope.filtered = $filter('filter')($scope.arrVaritions, $scope.elementId, true);
});

If you want to filter not the exact value just remove the 3rd true option:

$scope.filtered = $filter('filter')($scope.arrVaritions, $scope.elementId);