javascript

Collect books from array of objects and return collection of books as an array

let users = [{
    name: 'Anna',
    books: ['Bible', 'Harry Potter'],
    age: 21
}, {
    name: 'Bob',
    books: ['War and peace', 'Romeo and Juliet'],
    age: 26
}, {
    name: 'Alice',
    books: ['The Lord of the Rings', 'The Shining'],
    age: 18
}];

let books = users.reduce((acc, curr)=> {
    acc.push(...curr.books);
    return acc;
}, []);

console.log(books, "books");
Output
["Bible","Harry Potter","War and peace","Romeo and Juliet","The Lord of the Rings","The Shining"]
Was this helpful?