I have an object array with multiple variables.
let Books = [];
class Book {
constructor(ISBN, title, author, edition, publication, year, section) {
this.ISBN = ISBN;
this.title = title;
this.author = author;
this.publication = publication;
this.year = year;
this.edition = edition;
this.section = section;
}
}
//Example
ISBN = "978-1-56619-909-4";
title = "Software Engineering";
authors = ["author1", "author2"];
edition = 1;
publication = "Book publisher";
year = 2021;
section = "Engineering";
temp = new Book(ISBN, title, authors, edition, publication, year, section);
Books.push(temp);
I have a search bar on my website that I use to search and filter certain variables in the array based on user input. For example, if a user enters a word, I look for matches in the title variable and also in three other variables (author, publication and section) to get more results.
function search() {
filtered_results = [];
let searchText = searchBar.value;
if (searchText != "") {
let searchQuery = new RegExp(searchText, 'i');
temp_filter = Books.filter(book => searchQuery.test(book.title));
temp_filter = temp_filter.concat(Books.filter(book => searchQuery.test(book.author)));
temp_filter = temp_filter.concat(Books.filter(book => searchQuery.test(book.publication)));
temp_filter = temp_filter.concat(Books.filter(book => searchQuery.test(book.section)));
} else {
temp_filter = Books;
}
//Removing duplicates
filtered_results = removeDupicates(temp_filter);
// Display filtered results
displayResults(filtered_results);
}
The problem is sometimes I end up having duplicates because of matches in multiple variables. In the above example, I have the word 'Engineering' in both title and section, so it is displayed twice. I am trying to eliminate the duplicates using ISBN (since 2 books cannot have the same ISBN).
//Function to remove duplicates
function removeDupicates(array) {
let uniqueArray = [];
for (i = 0; i < array.length; i++) {
testID_t = array[i].ISBN;
let testID = new RegExp(testID_t);
if (!(testID.test(uniqueArray.ISBN))) {
uniqueArray.push(array[i]);
}
}
console.log(uniqueArray);
return uniqueArray;
}
But I still end up with duplicates because uniqueArray.ISBN is undefined and the test expression always evaluates to true. How do I check the ISBN values of all the elements of uniqueArray?
ISBN? That's a property ofBookobjects, not Arrays.Array.prototype.somefunction:!uniqueArray.some(book => testID.test(book.ISBN))