Write a function searchBooks which returns ALL the books written by a specific author and return the list of the book titles as a string, separated with comma if there are more than one titles. If these is no author in the library then return 'NOT FOUND'. Example dataset: library = [ { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254} ];.

Respuesta :

Answer:

var library=[{author:'Bill Gates',title:'The Road Ahead',libraryID:1254},

              {author:'Abdul Kalam',title:'India 2020',libraryID:1243},

              {author:'Abdul Kalam',title:'Ignited Minds',libraryID:1200},

              {author:'Abdul Kalam',title:'Inspiring thoughts',libraryID:1200},

              {author:'Aristotle',title:'Metaphysics',libraryID:1200}

              ];

  //author of the book to be searched

  var authorName='Abdul Kalam';

  //document.write() will write in the html page

  a=searchBooks(library,authorName);

  books=a[0];

  authorNames=a[1];

  //<h1></h1> is used to make heading Books

  document.write("Books:\n");

  for(i=0;i<books.length;i++)

      document.write(books[i]['author']+" --> "+books[i]['title']+" --> "+books[i]['libraryID']+"<br>");

  document.write("Titles:\n"+a[1]);

  function searchBooks(library,authorName){

      //empty string to assign book names

      list_of_titles='';

      books=[];

      //reading each book from 0th position to last

      for(i=0;i<library.length;i++){

          //if author is authorName then add it to list_of_titles

          if(library[i]['author']==authorName){

              books.push(library[i]);

              list_of_titles+=library[i]['title']+",";

          }

      }

      //removing the last comma

      list_of_titles=list_of_titles.slice(0,-1);

      //if list_of_titles is empty return NOTFOUND

      if(list_of_titles=='')

          return 'NOT FOUND';

      //if books are found return list_of_titles

      else

          return [books,list_of_titles];

      //returning the list of books and titles

  }