|
21 | 21 |
|
22 | 22 | //Fetch comes built into the browser. Keep in mind that Fectch itself returns a promise. |
23 | 23 | 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. |
25 | 27 |
|
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 | + } |
27 | 35 |
|
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, ','); |
33 | 38 | } |
34 | 39 |
|
35 | 40 | 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; |
37 | 54 | } |
38 | 55 |
|
| 56 | + |
39 | 57 | const searchInput = document.querySelector('.search'); // Selects the class="search" in HTML. |
40 | 58 |
|
41 | 59 | const suggestions = document.querySelector('.suggestions'); // Selects the class="suggestions" in HTML. |
|
0 commit comments