Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Aggregate Array

 

Say you have a collection of authors in an array. Each author has a property of books which is a list of string (book titles). You need to create a list of all books by all authors and have them sorted them in alpha-numeric order.

Authors looks like this:


const authors =
[
    {
        name: 'Mark Twain',
        imageUrl: 'Images/Authors/mark-twain.jpg',
        books: ['The Adventures of Huckleberry Finn', 'Life on the Mississippi']
    },
    {
        name: 'Joseph Conrad',
        imageUrl: 'Images/Authors/joseph-conrad.jpg',
        books: ['Heart of Darkness']
    },
    {
        name: 'J.K Rowling',
        imageUrl: 'Images/Authors/jk-rowling.jpg',
        books: ['Harry Potter and the Sorcerers Stone']
    },
    {
        name: 'Stephen King',
        imageUrl: 'Images/Authors/stephen-king.jpg',
        books: ['The Shining', 'It']
    },
    {
        name: 'William Shakespeare',
        imageUrl: 'Images/Authors/william-shakespeare.jpg',
        books: ['Hamlet', 'Macbeth']
    },
    {
        name: 'Arthur C Clarke',
        imageUrl: 'Images/Authors/arthur-c-clarke.jpg',
        imageSource: 'Wikimedia Commons',
        books: ['2001', 'Rendevous with Rama']
    },
    {
        name: 'Isaas Asimov',
        imageUrl: 'Images/Authors/isaac-asimov.jpg',
        imageSource: 'Wikimedia Commons',
        books: ['The Gods Themselves', 'Robot Dreams', 'The Naked Sun']
    }
];

The new array should look like this:


const books =
[
    'The Adventures of Huckleberry Finn',
    'Life on the Mississippi',
    'Heart of Darkness'
    'Harry Potter and the Sorcerers Stone',
    'The Shining',
    'It',
    'Hamlet',
    'Macbeth'...etc...
];

        
            const authors = //shown above;
            let books = [];
            let output = "";

            authors.forEach((author) => { author.books.forEach((book) => { books.push(book); }); });
            books = books.sort();
            output = books.join(", ");
            $("#DemoContainer").html(output);