JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author.

Here is an example library structure:

let library = [
  { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
  { author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
  { author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];

This is my code snippet:

let library = [
  { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
  { author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
  { author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];

function searchBooks(library, author) {
  for (author in library) { //enumerate
    if (author in library) {
      let line = Object.values(library[0]) // find line of the wanted author
      let result = (line[0] + "," + line[1]) // store author name and title name
      return result
    } else {
      return "NOT FOUND"
    }
  }
}

console.log(searchBooks(library, 'Bill Gates'))

The output generated looks like this: Bill Gates,The Road Ahead

The challenge: Regardless of which author I input into the searchBook, it always returns Bill Gates as the first entry in the library. It seems to not be iterating through all entries. Why might this be happening?

Initially, I thought about avoiding hard coding [0] and [1] and instead using i and i++. However, this approach resulted in a

TypeError: Cannot convert undefined or null to object
error message.

Answer №1

Here are a few key points to keep in mind:

  1. Instead of using for (author in library), consider using of which evaluates each value in the array. In this case, we're naming that value book.
  2. It's advisable to make your result an array or collection so that you can easily store multiple responses.
  3. When checking for the author in the library object, use book.author == author to ensure that the author is a value of the object's author key.
  4. Since the result is an array, join the values with a newline. If the result array is empty (falsey), return the NOT FOUND message. Otherwise, return all the books.

let library = [
  { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
  { author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
  { author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];

function searchBooks(library, author) {
  let result = []

  for (let book of library) {
    if (book.author == author) {
      let line = Object.values(book)
      result.push(line[0] + "," + line[1])
    }
  }

  return result.join('\n') || 'NOT FOUND'
}

console.log(1, searchBooks(library, 'Carolann Camilo'))
console.log(2, searchBooks(library, 'Bill Gates'))
console.log(3, searchBooks(library, 'Oh boy'))

Note:

  • To avoid using Object.values, refer to this explanation.
  • If you want to filter specific books from the library, consider using filter. Check out this solution.
  • Another approach to iterating over the library is by using forEach. Learn more about it from this answer.

Answer №2

If you're looking to filter through an array in JavaScript, consider using the Array.filter method (check out MDN for more info):

const library = [
  { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
  { author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
  { author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];

console.log(findAuthor(library, `Bill Gates`));

function findAuthor(library, author) {
  return library.filter(book => book.author === author);
}

Answer №3

Using the forEach method, you can iterate through elements and compile multiple entries by the same author into a given result.


let bookshelf = [
  {author: 'J.K. Rowling', title: 'Harry Potter and the Sorcerer\'s Stone', libraryID: 1234 },
  { author: 'Stephen King', title: 'The Shining', libraryID: 5678 },
  { author: 'J.K. Rowling', title: 'Harry Potter and the Chamber of Secrets', libraryID: 9012 }
];
function findBooks(library, author) {
  let result = ""
  library.forEach(book => {
    if (book.author === author) {
      result += book.author+", "+book.title+"\n"
    }
  })
  return result
}

console.log(findBooks(bookshelf, "J.K. Rowling"))

Answer №4

Below is a functional version of the method you've proposed:

let library = [
    { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
    { author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
    { author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];

function searchBooks(library, author) {
    for (const book of library) { //browse through
        if (book.author === author) {
            let result = (book.author + "," + book.title) // save author and title
            return result
        }
    }
    return 'NOT FOUND'
}

console.log(searchBooks(library, 'Bill Gates'))

  • Start by looping through the books in the library, not just the authors.

  • Determine if the author of the book matches the desired author.

  • Then display the author and title of that book separated by a comma.

Keep in mind this will only provide the first match found, not all matches.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node's getRandomValues() function is throwing an "expected Uint8Array" error

Currently, I am experimenting with the getRandomValues() function to enhance an encryption REST API that I am developing for practice. My server is using Node, which means I do not have access to a window object containing the crypto object normally housin ...

How about: "Add random HTML content using jQuery each time the page is refreshed

Currently facing this issue: I implemented a jquery plugin fullPage.js by Alvaro Trigo on my website. The plugin script automatically inserts the html structure in certain elements... in my html I have: <div class="section fp-auto-height-responsive" ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Instructions for adding username/password authentication using Express ntlm

Attempting to set up username and password authentication using Express-ntlm. I've included the following code as middleware: app.use( ntlm({ domain: '<domainname>', domaincontroller: '<ldap url>', })); I haven't ...

Troubleshooting: Issues with jQuery's Class selector

Having trouble setting up an alert to trigger when a specific class anchor tag is clicked inside a div. This is what my HTML section looks like... <div id="foo"> <a class='bar' href='#'>Next</a> </div> And h ...

What is the best method for simultaneously listening to several events?

For instance, I am interested in setting up a situation where a callback is triggered only when ALL specified events occur: on(['aEvent', 'bEvent', 'cEvent'], callback) The callback function should receive an array (or objec ...

Looking for answers to a question about Handlebars in Node.js? Click on the following link to explore more

After successfully parsing my Shopify product items into a MongoDB database using a model, I am attempting to display them to the user using the express-handlebars package. However, I've encountered a small issue. I'm utilizing <td><a ...

Retrieve information from json, divide it, and transfer it to the chart for display

Greetings everyone! In my project, I am parsing a JSON file from an online API. However, I have encountered a roadblock while trying to split the data. Despite searching extensively on platforms like YouTube, I haven't been able to find a solution tha ...

Prevent a submit button from submitting a form using jQuery

I am working on developing a password manager similar to a chrome extension. The goal is to detect the username and password fields when a user tries to log in to a website, such as Facebook, and then prompt the user if they would like to save these creden ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

Creating "search result pages" with HTML, PHP, Javascript, and MySQL

Consider the scenario where you have a table with two columns: id and name, containing thousands of rows. You have a search engine that allows searching by free text, using the query: SELECT * FROM `table` WHERE `name` LIKE '%$search%' The res ...

The MUI Time picker fails to display the correct time value in the input field with proper formatting

My primary goal is to implement a MUI time picker with yup validation and react-hook-form. However, I am encountering an issue where the selected time from the time picker is not being updated in the text field as expected. https://i.sstatic.net/LVkgK.png ...

Cannot find a function within the Promise

Here is the code snippet I am working with: var c = function(address, abiJson){ var _ = this; this.data = { wallet: false, account:{ address: false }, contract:{ addre ...

Robotic Arm in Motion

GOAL: The aim of the code below is to create a robotic arm that consists of three layers (upper, lower, and middle), all connected to the base. There are four sliders provided to independently move each part except for the base which moves the entire arm. ...

Incorporating JSON into a ColdFusion program

I have a website that showcases different views for registered and non-registered users. I am currently redesigning the product navigation to make it easier to manage by using JSON format. My website is built on Mura CMS with ColdFusion. Although what I ...

The focal point of a Three JS rotation

My goal is to rotate the geometry around a pivot point and set that as the new definition of the geometry. I want the current rotationZ to become the new rotationZ 0 without having to keep editing the rotationZ. This way, when I create a new rotation task ...

The success method in the observable is failing to trigger

Could someone explain why the () success method is not triggering? It seems to be working fine when using forkjoin(). Shouldn't the success method fire every time, similar to a final method in a try-catch block? Note: Inline comments should also be c ...

Node.js environment variable returns a value of 'undefined'

One method I use to safeguard my bot tokens is by utilizing dotenv to keep them separate from the main app. However, a problem arises when running the code - the environment variables appear as undefined, resulting in an error message: Error: An invalid to ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...