edu edu - 1 month ago 8
AngularJS Question

How to check duplicate before adding to array


  1. hi, I got code, what can check duplicate when two same values are ALREADY in the list. How can I check duplicate before adding the second same value to list. ps. I'm coparing string values.

    var vals = $scope.todoDatat.map(function(item){ return item.time });
    var isDuplicate = vals.some(function (item, idx) {
    return vals.indexOf(item) !== idx;
    });


    if (isDuplicate) {

    $scope.errortext = 'time is a duplicate';

    } else{

    $scope.todoDatat.push({date: day, time: time, value: 15, arvo: arvosi});

    }

  2. When it founds a duplicate, it dont let me continue adding new values, that are not duplicates to the list. How can i continue add new values to the list, even when duplicate has found?



Thx beforehand =)

Tal Tal
Answer

Sound you looking for a solution like this:

        $scope.todoItems = ['13:00', '14:00', '15:00'];
        $scope.todoDatat = ['14:00', '22:00'];

        angular.forEach($scope.todoItems, function (item) {
            if ($scope.todoDatat.map(function (x) {return x;}).indexOf(item) >= 0) {
                console.log('Duplicate!');
                // $scope.errortext = 'time is a duplicate';
            } else {
                console.log('Not Duplicate');
                // $scope.todoDatat.push({date: day, time: time, value: 15, arvo: arvosi});
            }
        });

Hope it will help you.

Comments