filtered search in javascript

One way to perform filtered search in JavaScript is by using the filter() method on an array. The filter() method creates a new array with all elements that pass the test implemented by the provided function.

To perform a filtered search, you can use the filter() method on an array of objects and pass a callback function as an argument. The callback function will take each element of the array and test it based on a certain criterion. If the element meets the criterion, it will be added to the new array, which will be returned when the filtering is done.

Here is an example that demonstrates how to implement filtered search in JavaScript:

index.tsx
const items = [
    {
        name: "apple",
        category: "fruit"
    },
    {
        name: "carrot",
        category: "vegetable"
    },
    {
        name: "orange",
        category: "fruit"
    },
    {
        name: "broccoli",
        category: "vegetable"
    }
];

function filterItems(query) {
    return items.filter(function(item) {
        return item.name.toLowerCase().indexOf(query.toLowerCase()) !== -1;
    });
}

console.log(filterItems("car")); // filtered array will contain only "carrot" object
523 chars
27 lines

In this example, we have an array of objects that represent food items, with each item having a name and a category property. The filterItems() function takes a query string as input and returns an array of items that contain the query string in their name property. The filter() method iterates over each element of the items array and tests if the name property contains the query string using the indexOf() method. The toLowerCase() method is used to convert all strings to lowercase and ensure that the search is case-insensitive.

This is one way to perform a filtered search in JavaScript using the filter() method on an array.

gistlibby LogSnag