Vincent Prime Interview

by Matthew Vasallo

HTML

<ul id="theList">
    <li>6</li>
    <li>3</li>
    <li>1</li>
    <li>4</li>
    <li>7</li>
    <li>4</li>
    <li>2</li>
    <li>8</li>
    <li>9</li>
    <li>2</li>
</ul>

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 theListNumbers = [];

$(function(){
    toArray('#theList li', findDuplicate);
});

function toArray(element, callback) {
    $.each($(element),function(index, element){
        //console.log(element);
        theListNumbers.push( element.innerHTML );
    });
    callback(theListNumbers);
};    

function findDuplicate(array) {
    var tempArray = array.reverse();
    var duplicate = '';
    while ( tempArray.length > 0 ){
        var value = tempArray.pop();
        var indexOfDuplicate = tempArray.indexOf(value);
        if (indexOfDuplicate > -1) {
             alert(value);
             break;
        }
    }
};