Why the filter method is not working when filtering an array of objects requested from an API (Javascript)

I have been practicing some coding after some break. I'm trying to filter an array of objects from an api and creating a function the which will return me every word from the title of the fetch I'm making the request.

However, when I want to do the filter it shows that filter method is not recognized, and I don't know if its affected if you are filtering an array that you called from an api.

This is the code.

function titles(word){
    let sentence
    let array = []
    let api = ''
    let data = fetch(api)
    let response = data.then(res => res.json()).then(data => => { e.title}))
    array = array.concat(response)
    sentence = Promise.all(array.flat()).then(results => results.flat())
  const people = sentence.filter(e => e.title.includes(word))
    return people

However, returns an error message (see image)

But when I do the same on an array of objects the filter works well.

I appreciate any help, feedback and code improvement. Thanks in advance!

error message


  • Here we have to take a look at the part where you are trying to extract the data. Adding a proper way to fetch by converting it to JSON will help. using data.json() after which you can filter. Conforming with your code flow, now after this, you can use the filter option.

    You can find working code here

       async function titles(word) {
          const sentence = [];
          const api = "";
          const data = await fetch(api);
          const response = await data.json();
          const titles ={ title }) => title);
          const people = sentence.filter((title) => title.indexOf(word) > -1);
          return people;