Skip to content

Commit 477540d

Browse files
author
Justin Ramel
committed
filter list working
1 parent b17b932 commit 477540d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

06 - Type Ahead/index-START.html

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,45 @@
1818
<script>
1919
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
2020
let cities = []
21+
const input = document.querySelector('input')
22+
const resultsList = document.querySelector('ul')
23+
24+
function onKeypress (e) {
25+
const search = `${e.target.value}${e.key}`
26+
const results = find(search, cities)
27+
console.log('results', results)
28+
const items = results.reduce((acc, item) => acc = `${acc}<li>${item.state} - ${item.city}</li>`, '')
29+
resultsList.innerHTML = items
30+
}
31+
32+
function find (word, cities) {
33+
const regex = new RegExp(word, 'gi')
34+
return cities.filter(place => place.state.match(regex) ||
35+
place.city.match(regex))
36+
}
37+
38+
function numberWithCommas(x) {
39+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
40+
}
41+
42+
function updateList () {
43+
const results = find(this.value, cities)
44+
const regex = new RegExp(this.value, 'gi')
45+
const items = results.reduce((acc, item) => {
46+
const stateName = item.state.replace(regex, `<span class="hl">${this.value}</span>`)
47+
const cityName = item.city.replace(regex, `<span class="hl">${this.value}</span>`)
48+
acc = `${acc}<li>
49+
<span class"name">${stateName} - ${cityName}</span>
50+
<span class="population">${numberWithCommas(item.population)}</span>
51+
</li>`
52+
return acc
53+
}, '')
54+
resultsList.innerHTML = items
55+
}
56+
57+
input.addEventListener('change', updateList)
58+
input.addEventListener('keyup', updateList)
59+
2160
fetch(endpoint)
2261
.then(response => response.json())
2362
.then(json => cities = json)

0 commit comments

Comments
 (0)