Cengage Angular First Duplicate MPV

by Matthew Vasallo

HTML

<!-- Add AngularJS code to display the list -->
<!-- Add code to mark the first duplicate in the list --->
<div ng-app="DuplicateApp" ng-controller="DuplicateController">
<ul id="theList">
    <li ng-repeat="number in numberList track by $index">{{number}}</li>
</ul>
<button type="button" ng-click='findFirstDuplicate()'>Find first duplicate! {{mattVal}}</button>
    <div>First Duplicate is: {{firstDuplicate}}</div>
    <input ng-model='mattVal'>test</input>
</div>

JavaScript

/*
Write an algorithm that will find the first duplicate in a list on the page.
For example we would return 4, for the list above.
*/
var app = angular.module("DuplicateApp", []);

app.controller("DuplicateController", function($scope){
    var numbers = [
        6,
        1,
        0,
        4,
        7,
        4,
        2,
        8,
        9,
        2
    ];
    $scope.numberList = numbers;
    $scope.mattVal = 'good times';
    
    $scope.findFirstDuplicate = function(){
        var numbersAlreadySeen = [];
        numbers.every(function(value, index){
            if(numbersAlreadySeen.indexOf(value) === -1){
                numbersAlreadySeen.push(value);
            }
            else{
                $scope.firstDuplicate = value;
                alert('matt says ' + $scope.mattVal);
                return false;
            }
            return true
        });
    };
});