Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check For Uniqueness in Array, Push To Array if Unique

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):

  1. Check if todo is already in todos

    1a. If it does exisit, don't push, display alert

  2. Check if todo is not blank

    2a. If it is blank, don't push, display alert

  3. 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

like image 257
James Cliburn Avatar asked Aug 18 '13 10:08

James Cliburn


People also ask

How do you push data in an array without duplicates?

To prevent adding duplicates to an array:Use the Array. includes() method to check if the value is not present in the array. If the value is not present, add it to the array using the push() method. The array will not contain any duplicate values.


1 Answers

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];
  }
};
like image 81
Mehdi Avatar answered Oct 07 '22 21:10

Mehdi