Digamos que tengo una matriz de 5 objetos, cada uno con 2 claves (por ejemplo, 'título' y 'autor').
Quiero verificar la veracidad de que existen 3 títulos ESPECÍFICOS en la matriz.
¿Cuál es la mejor manera de hacer eso?
Tengo lo siguiente... pero no parece muy eficiente:
const books = [ { title: 'Book1', author: 'Author1' }, { title: 'Book2', author: 'Author2' }, { title: 'Book3', author: 'Author3' }, { title: 'Book4', author: 'Author4' }, { title: 'Book5', author: 'Author5' }, ]; const certainBooks = books.some((b) => b.title === 'Book2') && books.some((b) => b.title === 'Book3') && books.some((b) => b.title === 'Book5') if (certainBooks) { // Do stuff }Si los valores y la cantidad de títulos son dinámicos, podría valer la pena crear un índice de títulos en la matriz; algo con complejidad de tiempo O(1) para búsquedas más rápidas
const books = [ { title: 'Book1', author: 'Author1' }, { title: 'Book2', author: 'Author2' }, { title: 'Book3', author: 'Author3' }, { title: 'Book4', author: 'Author4' }, { title: 'Book5', author: 'Author5' }, ]; const titleIndex = new Set(books.map(({ title }) => title)); const titlesExist = (...titles) => titles.every(title => titleIndex.has(title)) console.log("Book2, Book3, Book5:", titlesExist("Book2", "Book3", "Book5")); console.log("Book1:", titlesExist("Book1")); console.log("Book5, Book6:", titlesExist("Book5", "Book6"));Un enfoque más general sería asignar los libros a sus títulos y luego verificar que .every todos los títulos que está buscando.
const books = [ { title: 'Book1', author: 'Author1' }, { title: 'Book2', author: 'Author2' }, { title: 'Book3', author: 'Author3' }, { title: 'Book4', author: 'Author4' }, { title: 'Book5', author: 'Author5' }, ]; const titles = books.map(({ title }) => title); const toFind = ['Book2', 'Book3', 'Book5']; if (toFind.every(title => titles.includes(title))) { console.log('do stuff'); } Si la matriz de libros es grande, podría beneficiarse al hacer que los titles sean un Conjunto en lugar de una matriz: Set#has es más rápido que Array#includes cuando hay muchos elementos.
Podrías recorrerlos
const books = [ { title: "Book1", author: "Author1" }, { title: "Book2", author: "Author2" }, { title: "Book3", author: "Author3" }, { title: "Book4", author: "Author4" }, { title: "Book5", author: "Author5" }, ]; const booksNeeded = ["Book2", "Book3", "Book4"]; for (let book of books) { const lookForIndex = booksNeeded.findIndex( (title) => title.toLowerCase() === book.title.toLowerCase() ); if (lookForIndex !== -1) { booksNeeded.splice(lookForIndex, 1); } if (!booksNeeded.length) { break; // Early break if all the books has been found } } if (!booksNeeded.length) { console.log("Do Something"); } else { console.log("Something else"); }