2

I have an array called myLibrary and an Object constructor function, which creates Book objects with properties such as title, author, pages, status (read or not read). Whenever I create an object using the constructor, I push that object to myLibrary array.

However, I need to find a way to associate those book objects inside of myLibrary array with actual DOM elements on the page (called book cards) for implementing the remove button. Once the user clicks the remove button, that is present on every book card container, I want to remove the book card not only visually, but from myLibrary array as well.

I've tried using indexOf method on the array to find the index of an object, but it always returned the value -1.

let myLibrary = [];

function Book(title, author, pages, isRead) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.isRead = isRead;
    this.index = myLibrary.indexOf(this); // returns "-1"
}

function addBookToLibrary() {
    if (title.value === "" || author.value === "" || pages.value === "" || parseInt(pages.value) > 17868) return 
    myLibrary.push(new Book(title.value, author.value, pages.value, isRead.checked));

    createBookCardElement();
}

function createBookCardElement() {
    const bookCard = document.createElement("div");

    createParagraphElements(bookCard);
    createChangeStatusButtonElement(bookCard);
    createRemoveButtonElement(bookCard);

    bookCard.classList.add("book-card");
    
    library.appendChild(bookCard);
}

Pavlukan
  • 21
  • 1
  • You need to use [`findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) instead e.g. `myLibrary.findIndex(o => o.title == this.title && o.author == this.author)` – Nick Oct 08 '22 at 06:19

0 Answers0