class Author {
constructor(name, birth, death, nationality) {
this.name = name,
this.birth = birth,
this.death = death,
this.nationality = nationality
}
}
class Book {
constructor(title, pubDate, authorKey) {
this.title = title,
this.pubDate = pubDate,
this.authorKey = authorKey
}
}
authors = [
new Author({first: "William", last: "Shakespeare"}, 1564, 1616, "English"),
new Author({first: "Francis", last: "Bacon"}, 1561, 1626, "English"),
new Author({first: "Thomas", last: "More"}, 1478, 1535, "English"),
new Author({first: "Geoffrey", last: "Chaucer"}, 1343, 1400, "English"),
new Author({first: "Mary", last: "Shelley"}, 1797, 1851, "English"),
new Author({first: "Jane", last: "Austen"}, 1775, 1817, "English"),
new Author({first: "JK", last: "Rowling"}, 1965, 0, "English"),
new Author({first: "George", last: "Orwell"}, 1797, 1851, "English"),
new Author({first: "Charles", last: "Dickens"}, 1797, 1851, "English"),
new Author({first: "George", last: "Eliot"}, 1819, 1880, "English")
];
books = [
new Book("Middlemarch", 1871, 9),
new Book("Silas Marner", 1861, 9),
new Book("A Christmas Tale", 1843, 8),
new Book("Oliver Twist", 1837, 8),
new Book("Great Expectations", 1860, 8),
new Book("A Tale of Two Cities", 1859, 8),
new Book("David Copperfield", 1849, 8),
new Book("Nineteen Eighty-Four", 1949, 7),
new Book("Animal Farm", 1945, 7),
new Book("The Complete Plays", 2016, 1),
new Book("Four Great Comedies", 2009, 1),
new Book("Essays", 1597, 1),
new Book("Novum Organum Scientiarum", 1620, 1),
new Book("A Merry Jest ", 1516, 2),
new Book("Utopia", 1516, 2),
new Book("The Canterbury Tales", 1400, 3),
new Book("Frankenstein: or, The Modern Prometheus", 1818, 4),
new Book("Sense and Sensibility ", 1811, 5),
new Book("Pride and Prejudice ", 1813, 5),
new Book("Harry Potter and the Philosopher's Stone ", 1997, 6),
new Book("Harry Potter and the Chamber of Secrets", 1998, 6),
new Book("Harry Potter and the Prisoner of Azkaban", 1999, 6),
new Book("Harry Potter and the Goblet of Fire", 2000, 6),
];
for (let i = 0; i < books.length; i++) {
let auth = authors.filter( (elem, index) => books[i].authorKey === index);
console.log(`title: ${books[i].title}, author: ${auth[0].name.first} ${auth[0].name.last}`);
};
books.forEach((book, index) => {
let auth = authors.filter( (elem, i) => book.authorKey === i);
console.log(`title: ${book.title}, author: ${auth[0].name.first} ${auth[0].name.last}`);
});
Saturday, July 1, 2017
forEach() with filter() Lookup
Let's avoid some data duplication and use a keyed lookup to retrieve a book's author.