Title: Match() on object array
Tags: javascript;html;arrays;string
Question: I have an object array with multiple variables.
let Books = [];
class Book {
constructor(docID, title, author, edition, publication, year) {
this.docID = docID;
this.title = title;
this.author = author;
this.publication = publication;
this.year = year;
this.edition = edition;
//Example
ISBN = "978-1-56619-909-4";
title = "Book title";
authors = ["author1", "author2"];
edition = 1;
publication = "Book publisher";
year = 2021;
temp = new Book(ISBN, title, authors, edition, publication, year);
Books.push(temp);
I have a search bar and I need to search and filter certain variables in the array. For example, I need to search the title variable for matches and filter only those that match the input. I use match() to look for matches.
let searchText = "title"; //Given by user
if (searchText != "") {
let searchQuery = new RegExp(searchText, 'i');
filtered_results = Books.match(searchQuery);
} else {
filtered_results = Books;
However, I get an error saying match() is not available for Books (because it's not a string). If I use it on my string variable it works (Books[1].title.match()). In that case, I need to use a loop and look for a match in every iteration.
Is there an efficient way of doing this without a loop? Because I need to check for matches in author and publication if the title doesn't match. I don't think looping through the object every time is an efficient way of doing this.
Comment: I need to filter the Books object which matches the search criteria (either title, author or publication)

Comment: I know. Using it on a string works. But it's not an efficient way as I mentioned. I just want to know if there is a similar function or workaround that lets me look for matches directly on the object.

Comment: what is expected output ?

Comment: `match` works on string. `Books` is an array

Here is the accepted answer: You should use Array.prototype.filter
To filter through your array of books,
let searchQuery = new RegExp(searchText, 'i');
filtered_results = Books.filter(book =&gt; searchQuery.test(book.title));
Here, we are checking through every book in the Books array, then using the RegExp to .test if the book title is a match
You also don't need the if conditional, the RegExp will return all the books in the case of an empty string.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:04/10/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><html><arrays><string>', 'Title': 'Match() on object array', 'ViewCount': 56, 'id': 67031743, 'user_AboutMe': '', 'user_AccountId': 21000579.0, 'user_DisplayName': 'Gekkouga', 'user_Reputation': 19.0, 'user_Views': 3.0, 'user_id': 15431472.0}}