I am basically trying to prevent duplicate objects from being created by iterating through the myLibrary array. If user input is a unique title, then add to array. If not, then deny entry.
No matter what I try, I get to the point where my code tells me a duplicate exists but still adds the duplicate object.
I am obviously new to this. Thank you in advance for any help.
let myLibrary = [];
class BookInfo {
constructor(title, author, pages, genre) {
this.title = title,
this.author = author,
this.pages = pages,
this.genre = genre
};
};
// Add new book to library array:
const addBook = function() {
let title = document.getElementById("title");
let author = document.getElementById("author");
let pages = document.getElementById("pages");
let genre = document.getElementById("genre");
document.getElementById("Submit").addEventListener('click', (e) => {
e.preventDefault();
const newBook = new BookInfo(title.value, author.value, pages.value, genre.value);
if (myLibrary.length === 0) {
myLibrary.push(newBook); // Add first book to library.
alert(`${title.value} has been added to your library!`);
document.querySelector('form').reset(); // clear form after submit.
} else {
myLibrary.forEach(book => {
console.log(newBook.title);
if (book.title === newBook.title) { // Dup exists.
alert(`${title.value} already exists in your library.`);
document.querySelector('form').reset(); // clear form after submit.
return;
} else {
myLibrary.push(newBook);
alert(`${title.value} has been added to your library.`);
document.querySelector('form').reset(); // clear form after submit.
return;
}
})
};
});
};
addBook();
<form>
<input type="text" id="title">
<input type="text" id="author">
<input type="number" id="pages">
<input type="text" id="genre">
<input type="button" value="Submit" id="Submit">
</form>