I'm confused about a function outlined in a module of my bootcamp

Viewed 22

I'm working with express.js and wondering how this function returns all the pertinent data about an animal. The query is searching an animal by name, it returns all of the info about the animal but I don't know how the function works.

function filterByQuery(query, animalsArray) {
    let filteredResults = animalsArray;
    if (query.diet) {
        filteredResults = filteredResults.filter(animal => animal.diet === query.diet);
    }
    if (query.species) {
        filteredResults = filteredResults.filter(animal => animal.species === query.species);
    }
    if (query.name) {
        filteredResults = filteredResults.filter(animal => animal.name === query.name)
    }
    return filteredResults;
}
1 Answers

So you have an array of animal objects/classes. You are trying to limit the array to the items that match. So the items you can match are diet, species, and name. Not all of them are required so you are doing a check to see what ones were specified.

The if statements are a truthy checks to see if the value exists in the query. So if (query.diet) { is saying is diet a truthy value? Yes, then we should apply this filter check.

The Array filter method loops over every index in the array. If true is returned it keeps it. If false is returned it ignores it.

So when it does animal.diet === query.diet it returns the true or false and determines if the animal object has the same requirement as the query is asking for.

The final result of the function is a new array that has the animal objects that match the query parameters provided.

Related