I'm learning TDD and I would like to create a function to expected this result.
//What I expect
[
{book_id: 1, name:'NameBook', average: x},
{book_id: 2, name:'NameBook', average: x},
{book_id: 3, name:'NameBook', average: x},
{book_id: 4, name:'NameBook', average: x},
{book_id: 5, name:'NameBook', average: x},
{book_id: 6, name:'NameBook', average: x},
{book_id: 7, name:'NameBook', average: x},
]
I got to merge two objects with the filter function but I'm having difficulties calculating the average and sum of these values where the id's are equal.
I'm posting here what I got to do https://jsfiddle.net/thiagolmoraes/5xsk7Lgw/1/
Anyone can help me.
const getBooks = () => {
return [
{ id: 1, name: 'Python Data Science' },
{ id: 2, name: 'Python Machine Learning' },
{ id: 3, name: 'Development Flask' },
{ id: 4, name: 'Mongo Database' },
{ id: 5, name: 'ULM for Dummies' },
{ id: 6, name: 'Java for Dummies' },
{ id: 7, name: 'Learn Rust in 2 hours' },
]
}
const getRating = () => {
return [
{ book_id: 1, client_id: 1, rating: 4.5 },
{ book_id: 1, client_id: 4, rating: 5 },
{ book_id: 1, client_id: 25, rating: 5 },
{ book_id: 1, client_id: 2112, rating: 4 },
{ book_id: 2, client_id: 34, rating: 3 },
{ book_id: 2, client_id: 123, rating: 4 },
{ book_id: 2, client_id: 23, rating: 4 },
{ book_id: 2, client_id: 255, rating: 4 },
{ book_id: 3, client_id: 98, rating: 2 },
{ book_id: 3, client_id: 45, rating: 1 },
{ book_id: 3, client_id: 223, rating: 3 },
{ book_id: 3, client_id: 213, rating: 1.5 },
{ book_id: 4, client_id: 652, rating: 4.5 },
{ book_id: 4, client_id: 42, rating: 4.5 },
{ book_id: 4, client_id: 562, rating: 4.5 },
{ book_id: 5, client_id: 2, rating: 5 },
{ book_id: 5, client_id: 2, rating: 5 },
{ book_id: 5, client_id: 2, rating: 5 },
{ book_id: 6, client_id: 2, rating: 4.5 },
{ book_id: 6, client_id: 2, rating: 4.5 },
{ book_id: 6, client_id: 2, rating: 4.5 },
{ book_id: 7, client_id: 2, rating: 4.5 },
{ book_id: 7, client_id: 2, rating: 4.5 },
{ book_id: 7, client_id: 2, rating: 4.5 },
{ book_id: 7, client_id: 2, rating: 4.5 },
{ book_id: 7, client_id: 2, rating: 4.5 },
]
}
const getBooksWithRatings = () => {
return getBooks().map((book) => {
book.ratings = getRating().filter((r) => r.book_id === book.id);
return book;
});
};
console.log(getBooksWithRatings())