typeahead.js autocomplete with two-dimensional array Ajax call

Using the typeahead.js library to create an autocomplete input from a two-dimensional array that was fetched with an Ajax request.

typeahead.js is created by Twitter to “provide a strong foundation for building robust typeaheads”. In this case, a typeahead is an autocomplete/auto-suggest input.

 

CodePen link.

This example is for NBA teams typeahead using the API endpoint https://api.nbastatr.com/teams/ which provides a two-dimensional array.

Guide

Define the array to store what you want to search and then create the Ajax call for the data. Then a loop is done to fill the created array ensuring that no data is duplicated into the array:

let teams = [];

$.ajax({
    url: 'https://api.nbastatr.com/teams/',
    type: 'GET',
    dataType: 'json',
    success: function (json) {
        let arrayLength = json.length;
        for (let i = 0; i < arrayLength; i++) {
            if (!teams.includes(json[i]['name_full'])) {
                teams.push(json[i]['name_full']);
            }
        }
        return teams;
    }
});

Now the substring match function is provided by typeahead.js here:

let substringMatcher = function (strs) {
    return function findMatches(q, cb) {
        let matches, substringRegex;
        matches = [];
        substrRegex = new RegExp(q, 'i');
        $.each(strs, function (i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });
        cb(matches);
    };
};

Finally initialize the typeahead and use the team’s array that got built.

$('#nba-teams.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'teams',
        source: substringMatcher(teams)
    }
);

The input HMTL:

 <div id="nba-teams">
   <input class="typeahead form-control" type="text" placeholder="NBA teams">
</div>

The typeahead input is complete.