skip to Main Content

I write this function in js to retrieve array of objects from my data array but it does not return all the data in the array that meet the query

this is a part of my data array. The original one contains 1536 objects.

const jokes = [
    {
        "id": 1,
        "joke": "What do you call people who pretend to be Irish on St. Patrick's Day? Counterfitz"
    },
    {
        "id": 2,
        "joke": "What did one wall say to the other wall? I`ll meet you at the corner."
    },
    {
        "id": 3,
        "joke": "I thought about starting a business selling halos... ...but the cost of overheads was too high."
    },
    {
        "id": 4,
        "joke": "What happens if you pass gas in church? You have to sit in your own pew."
    },
    {
        "id": 5,
        "joke": "What's a dog's favorite mode of transportation? A waggin'"
    },
    {
        "id": 6,
        "joke": "Why couldn't the melons be together? Everyone knows melons cantaloupe."
    }
]

and this is the function that I tried

const findJokes = (query) => {
    let jokesFound = jokes.filter((joke) => joke.joke.includes(query))
    return jokesFound;
}

when I query for "how" as an example, it returns 24 objects but it should return 132 objects. is there a better way to write this function?

2

Answers


  1. The .includes method use Strict equality when search into the sentence, so "how" is different to "How".

    Your code is correct, just need a small modification:

    const findJokes = (query) => {
        let jokesFound = jokes.filter((joke) => joke.joke.toLowerCase().includes(query.toLowerCase()))
        return jokesFound;
    }
    

    With this, you are going to compare always lower case letters.

    Login or Signup to reply.
  2. Use a case-insensitive regex:

    const jokes =  [{"id":1,"joke":"What do you call people who pretend to be Irish on St. Patrick's Day? Counterfitz"},{"id":2,"joke":"What did one wall say to the other wall? I`ll meet you at the corner."},{"id":3,"joke":"I thought about starting a business selling halos... ...but the cost of overheads was too high."},{"id":4,"joke":"What happens if you pass gas in church? You have to sit in your own pew."},{"id":5,"joke":"What's a dog's favorite mode of transportation? A waggin'"},{"id":6,"joke":"Why couldn't the melons be together? Everyone knows melons cantaloupe."}]
    
    const findJokes = query => 
      jokes.filter(({joke}) => joke.match(new RegExp(query,'i')))
    
    console.log(findJokes('DOG'))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search