Filter interview question

by ocorpening

HTML

<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>

JavaScript

// write a function 'filter' which will take a space-separated string of terms and return the array of matching records
var records = [
    { name: "Bob Allen", title: "The Programmer "},
    { name: "Alice Freeman", description: "Analyst"},
    { name: "Peter Fowler", desc: "Project Manager"}
];
filter("bob prog", records, "expect one record");
filter("bob fool", records, "expect no records");
filter("bob alice", records, "expect no records");
filter("programmer", records, "expect one record");
filter("e", records, "expect three records");

// Returns the array of records with values matching each of the query terms
function filter(query, records, expected)
{
    this.query = query.toLowerCase().split(" "); // store query on global object
    var resultArray = $.map(records, isRecordMatching);
    
    // output results
    console.log("Results expected = " + expected + ", found = ");
    $.each(resultArray, function(key, val)
    {
        console.log(val);
    });
}

// Process each record such as this first one:
//    {
//        name: "Bob Allen",
//        title: "The Programmer "
//    }
function isRecordMatching(record)
{
    var matches = 0;
    // loop thru query terms ("bob", "Prog"), if all are found in one of the object elements then record is a match
    this.query.forEach(function(queryElem)
    {
        if (isQueryTermMatch(record, queryElem))
        {
            matches++;
        }
    });
    if (matches === this.query.length) return record;
    else return null; // removes record from array
}

function isQueryTermMatch(targetRec, term)
{
    var found = false;
    // loop thru record objects, first is {name: "Bob Allen"}, if term is found return true;
    var resultArray = $.each(targetRec, function(key, val)
    {
        // first time val is "Bob" second time is "Allen", we want every queryTerm present in one of these once at least
        if (val.toLowerCase().indexOf(term) !== -1)
        {
            found = true;
            return...