K
K
KOPC18862014-11-26 15:36:39
JavaScript
KOPC1886, 2014-11-26 15:36:39

How to check if an element exists in an array?

Hello!
It is impossible to make through indexOf.
Here is the code

$scope.selectedEditor = function(user)
            {
                user.originalObject.id = user.originalObject.id * 1;
                if($scope.selectedEditors.indexOf(user.originalObject.id) === -1)
                {
                    $scope.selectedEditors.push({
                        id: user.originalObject.id,
                        label: user.originalObject.label
                    });
                }
                console.log($scope.selectedEditors);
            }

<div id="selectedEditors">
                                <div class="selected_user" ng-repeat="editor in selectedCategory.editors">
                                    <span class="user">{{editor.label}}</span>
                                    <span class="delete_chosen glyphicon glyphicon-remove" ng-click="deleteEditor($index)" title="Удалить"></span>
                                </div>
                            </div>

When adding the same user, this user is added to the array again. And I need to make a check so that the users are not repeated. If there is one already in the array, then do not add it. And if not, then add it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir San, 2014-11-26
@KwI

user you have is an object that is not a primitive, and indexOf will not work with it.
Options:
1) Keep an array with user ids in parallel and check for the presence of id in it
2) Pass through the array and compare each element with a new one by id.
or think of something else

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question