1

I have an Array and this array contains some Id's. I would like to filter my result according to Id's.

For Example please see the below code snippet. How can I show the records which 'StatusId' located in the 'ids' array? According to my example, I want to list only:

AAA BBB CCC

<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<script>
    angular.module('myApp', []).controller('ctrl', function ($scope) {

        $scope.ids = [{
            "id": 1
        }, {
            "id": 2
        }, {
            "id": 3
        }]

        $scope.records = [
            {
                "Name": "AAA",
                "StatusId": 1
            },
            {
                "Name": "BBB",
                "StatusId": 1
            },
            {
                "Name": "CCC",
                "StatusId": 2
            },
            {
                "Name": "DDD",
                "StatusId": 4
            },
            {
                "Name": "EEE",
                "StatusId": 4
            },
]


    });
</script>


<body>
    <div id="idctrl" ng-app="myApp" ng-controller="ctrl">
        <ul>
            <li ng-repeat="x in records">
                {{ x.Name }}
            </li>
        </ul>
    </div>
</body>

</html>

1

1 Answer 1

1

You can use the javascript 'filter' function:

records = $scope.records.filter((record) => {
    return record.StatusId === 1
});

This will return a new array that only contains records with a StatusId of 1. You can these use this updated array to display your desired records.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry I'm not clear. I've added your function into my code but the result hasn't changed.
@Grcn Arrays have a filter function that takes a function as input which should return true or false. It passes each element of the array through that function provided, and returns a new array of the elements that returned true. Read about it here.
Just an FYI, if you're working with arrow functions, and the function just returns a value, you can write it like this: (record)=>record.StatusId === 1 (or as record=>record.StatusId === 1, since there's exactly one parameter)
Thank you guys. I understand the point and have solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.