Skip to content

Commit c4ce5fe

Browse files
committed
Finished
1 parent 80e6117 commit c4ce5fe

2 files changed

Lines changed: 26 additions & 69 deletions

File tree

06 - Type Ahead/index-FINISHED.html

Lines changed: 0 additions & 61 deletions
This file was deleted.

06 - Type Ahead/index-START.html

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,39 @@
2121

2222
//Fetch comes built into the browser. Keep in mind that Fectch itself returns a promise.
2323
fetch(endpoint)
24-
.then(promise => promise.json()) // The promise needs to be converted to json. So access the json method that comes back with the promise and do another .then() which will return another promise.
24+
// The promise needs to be converted to json. So access the json method that comes back with the promise and do another .then() which will return another promise.
25+
.then(promise => promise.json())
26+
.then(data => cities.push(...data)); // We then push the data that comes back into the cities array. Now the data can be accessed by calling the cities variable.
2527

26-
.then(data => cities.push(...data)) // We then push the data that comes back into the cities array. Now the data can be accessed by calling the cities variable.
28+
function findMatches(wordToMatch, cities) {
29+
return cities.filter(place => {
30+
// here we need to figure out if the city or state matches what was searched
31+
const regex = new RegExp(wordToMatch, 'gi');
32+
return place.city.match(regex) || place.state.match(regex)
33+
});
34+
}
2735

28-
function findMatch(wordsToMatch, cities) {
29-
return cities.filter(place => {
30-
const regex = new RegExp(wordsToMatch, 'gi');
31-
return place.city.match(regex) || place.state.match(regex);
32-
});
36+
function numberWithCommas(x) {
37+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
3338
}
3439

3540
function displayMatches() {
36-
41+
const matchArray = findMatches(this.value, cities);
42+
const html = matchArray.map(place => {
43+
const regex = new RegExp(this.value, 'gi');
44+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
45+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
46+
return `
47+
<li>
48+
<span class="name">${cityName}, ${stateName}</span>
49+
<span class="population">${numberWithCommas(place.population)}</span>
50+
</li>
51+
`;
52+
}).join('');
53+
suggestions.innerHTML = html;
3754
}
3855

56+
3957
const searchInput = document.querySelector('.search'); // Selects the class="search" in HTML.
4058

4159
const suggestions = document.querySelector('.suggestions'); // Selects the class="suggestions" in HTML.

0 commit comments

Comments
 (0)