To return only the array element(s) on which a text search matched, you can use the filter() method in JavaScript. The filter() method creates a new array with all elements that pass the provided test (callback) function. In this case, the test function will check if the element contains the desired text. Here's an example:

// Sample array of objects const data = [ { id: 1, name: 'John Doe', age: 30 }, { id: 2, name: 'Jane Smith', age: 25 }, { id: 3, name: 'Bob Johnson', age: 35 }, // Add more objects as needed ]; // Function to search for a text in the 'name' property of the objects function searchByName(array, searchText) { return array.filter(item =>; } const searchText = 'John'; const searchResult = searchByName(data, searchText); console.log(searchResult);

In this example, the searchByName() function takes the array and the searchText as arguments. It uses the filter() method to create a new array containing only the elements that have the searchText in their name property.

When you run the code with searchText = 'John', it will return an array containing the object with the name 'John Doe':

[ { id: 1, name: 'John Doe', age: 30 } ]

If no match is found, the function will return an empty array.

You can adapt this example to your specific data structure and use case. The key is to define the appropriate test function inside the filter() method to determine whether an element should be included in the result array based on your text search criteria.

Have questions or queries?
Get in Touch