Check For Uniqueness in Array, Push To Array if Unique
angularjs, arrays, javascript, push
Solution
use `Array.indexOf` this way:
$scope.addTodo = function(){
$scope.isVisible = true;
if ($scope.todo) {
if ($scope.todos.indexOf($scope.todo) == -1) {
$scope.todos.push($scope.todo);
$scope.todo = '';
$scope.alert = $scope.alerts[1];
}else{
// $scope.todo is already in the $scope.todos array, alert the user
$scope.alert = $scope.alerts[3];
}
}else{
$scope.alert = $scope.alerts[0];
}
};
Problem
Using AngularJS, I'm creating an addTodo function in my app. I seem to be having trouble implementing a way to check the uniqueness of the object being added to the array, and having it followed by additional actions. So far I'm able to get the additional actions working, but not the initial check for uniqueness. How can I implement the check for uniqueness action and then have it followed by the additional actions? The addTodo function I'm trying to create flows like this (Bold means not implemented): Check if todo is already in todos 1a. If it does exisit, don't push, display alert Check if todo is not blank 2a. If it is blank, don't push, display alert If unique and not blank, push to todos, display success message Current addTodo function (without unqiueness check): ``` $scope.addTodo = function(){ $scope.isVisible = true; if ($scope.todo) { $scope.todos.push($scope.todo); $scope.todo = ''; $scope.alert = $scope.alerts[1]; }else{ $scope.alert = $scope.alerts[0]; } }; ``` Note 1: `$scope.alert` and `$scope.alerts` are used to display certain error messages; ``` $scope.alerts[0] ``` "Please add text to your task." ``` $scope.alerts[1] ``` "Added a new task!" The alert I want to display if the task being added already exists is ``` $scope.alerts[3] ``` "Task already in list." Note 2: `$scope.isVisible` toggles the visibility of the alert