0

I am following Wes Bos' javascript 30 course and i m on day 6 "Type Ahead". In this project im supposed to build a search bar that gives suggestions on typing down names. For this first an array of data was first brought in using fetch api. Then a function was made that takes the search item and the entire array as argument and then returns an array of all the array items that match the search input.

My problem is that when i try to call that function and give it relevant arguments, it returns an empty array. But when i call the same function on the console of the browser dev tools, it gives the required result.

On calling the function findMatches in the code itself:

const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cityName = document.getElementById('cities');
const cities = [];
fetch(endpoint).then(data => data.json()).then(data => cities.push(...data));

//cities  contain an array of objects containing city names with other information


// this function uses regular expression to match entered value with values in the array
function findMatches(wordToMatch, cities) {
  return cities.filter(place => {
    const regex = new RegExp(wordToMatch, 'gi');
    return place.city.match(regex) || place.state.match(regex)
  });
}

// calling findMatches function with a sample input to compare with cities array and storing it in result
const result = findMatches("New", cities);
// checking values of result
console.log(result);

this is the result on console:

enter image description here

But when i do the same thing directly on console:

enter image description here

here it gives array of all objects having string "New" in their values.

Its literally same function just called in different ways. What am i doing wrong?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Harsha
  • 23
  • 6
  • 2
    `fetch()` is asynchronous, you're not waiting for it to finish before calling `findMatches()`. – Barmar Jul 05 '23 at 16:32

0 Answers0