How to check if there is an input of an array within another to avoid duplicating?

Asked

Viewed 76 times

0

Good morning, that’s my first question around here

I’m making an angled app using the google Books api and I need help.. I have a button that adds indices from the book array to the bookmark array, but I need to prevent the same book from being added to bookmarks, follow the code My question is about the condition I should use in the if case the book already exists in the favorites

  books = []
  favs = []

  addFav(i: number) {
    const title = this.books[i].volumeInfo.title

    if(???) {
      this.toastr.error('Este livro já consta nos seus favoritos!')
    } else {
      this.favs.push(this.books[i])
      this.toastr.success(`O livro "${title}" foi adicionado aos seus favoritos!`)
      console.log(this.favs)
    }
  }
  • 1

    use the find of the array object to verify this. Here on the site you have several questions about this, see the one that will help you: https://answall.com/q/363949/57220

  • Thanks buddy, I’ll take a look

  • You can also use a set that avoids duplicates

  • const exists = this.favs.find(i => i.volumeInfo.title == title) I did this and passed the exists inside the if, it worked! thank you very much

  • good that’s right ;)

1 answer

0

So if you notice, you already do that:

const title = this.books[i].volumeInfo.title

this line will fail if index i in the array this.books not existing with "cannot get . volumeInfo of Undefined"

This tells you if you do

if (this.books[i]) {
  // isto quer dizer que o livro com o index "i" existe no "this.books"
}

then, if we deny this condition:

if (!this.books[i]) {
  // NAO existe o index "i" na array "this.books"
}

You can, however, check before. The function would look like this:

books = [];
favs = [];
addFav(i: number) {
    const book = this.books[i]; // criamos uma variavel que nos retorne o "livro" em si

    if(book) { // vemos se a variavel tem um valor "truthy"
      this.toastr.error('Este livro já consta nos seus favoritos!')
    } else {
      const title = book.volumeInfo.title; // podemos usar a variavel criada anteriormente
      this.favs.push(this.books[i])
      this.toastr.success(`O livro "${title}" foi adicionado aos seus favoritos!`)
      console.log(this.favs)
    }
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.