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

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

Attempting to create a dynamic dropdown menu with animated effects triggered by a key press

I've been attempting to construct a menu that initially appears as a small icon in the corner. Upon pressing a key (currently set to click), the checkbox is activated, initiating the animation. Most of the menu and animation are functional at this po ...

I keep encountering an ENOENT error whenever I try to kick off the project using npm start in Next.js. Can someone help me figure out

Having an issue with Next.js, how can I resolve it? [email protected] start next start ▲ Next.js 14.0.2 Local: http://localhost:3000 [Error: ENOENT: no such file or directory, open 'C:\Users\capas\Desktop\00\React&b ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

I am experiencing issues with the middleware not functioning properly after implementing a custom application with Next.js

I'm currently diving into Next.js version 13 and attempting to customize the app based on the standard documentation. However, it seems that the middleware isn't being invoked as expected. I suspect there might be something wrong with my implemen ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

Using JavaScript to control a dropdown list based on the selection of another dropdown

Hello, I am new to programming and a JavaScript beginner seeking help from you all. I have two dropdown lists and I am attempting to manipulate one based on the selection of the other using JavaScript. Both dropdown lists contain time in hours denoting st ...

The download handler (php code) is being triggered multiple times within a single request

My PHP script is responsible for handling download requests. Clients can access this script using a GET request, as shown in the Javascript example below: if (true) { window.open('/download?mode=paper&fid=' + fid, '_blank'); re ...

"Experience the power of React Swiper 6.8.4 as it unveils its slides only during window resizing or when

I'm a beginner in the world of coding and react, and I've encountered an issue with Swiper 6.8.4 in my React app after implementing a FilterMethod. My goal was to create a Slider containing Projects/Images as Slides, allowing users to filter thes ...

Tips for achieving compatibility between systemjs module loading and .net mvc architecture

Upon finding the ng-book 2, I saw it as a promising resource to delve into Angular 2. Although I am new to module loaders and have minimal experience with npm and node, I find the terminology and assumed knowledge to be quite perplexing. I decided to use ...

How do I overwrite this calculation using JQuery?

I have a website: link There are two pages on my site that have the same div elements... I want one page to perform a certain calculation on the divs, and another page to perform a different calculation... New JavaScript Code: jQuery(document).ready(fu ...

Express.js routes are malfunctioning with jade/pug, causing frequent crashes and routing errors

Here is the code for my contact router: var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('contact'); }); module.exports = rou ...

Creating a large JSON file (4 GB) using Node.js

I am facing a challenge with handling a large json object (generated using the espree JavaScript parser, containing an array of objects). I have been trying to write it to a .json file, but every attempt fails due to memory allocation issues (even though m ...

Whoops! Unable to interpret properties from an undefined source while trying to retrieve 'get'

Every time I execute my program, I encounter the following error: Cannot read properties of undefined (reading 'get') TypeError: Cannot read properties of undefined (reading 'get') at Proxy.mounted (webpack-internal:///./node_module ...

Vue.js not responding to "mousedown.left" event listener

I am trying to assign different functionalities to right and left click on my custom element. Within the original code, I have set up event listeners for mouse clicks in the element file: container.addEventListener("mousedown", startDrag); conta ...

Why am I not seeing my views when trying to export them from a file in my routes folder?

I've been tinkering around with basic routing in ExpressJS and up to this point, I have implemented two routes: app.get('/', function(req,res) { res.render('index'); }); app.get('/pics', function(req,res) { res.rend ...

Having trouble importing the named export `{module}` from a non-ECMAScript module with TipTap and Nuxt?

I'm using TipTap with Nuxt and running into some issues that I can't seem to resolve. Despite following suggestions from the repository's issues, I keep encountering these specific errors: ERROR in /Volumes/Projects/nuxt/candy-hub-lerna/no ...

Likelihood of triggering a function based on percentage

Hey everyone, I'm looking to add some randomness to the buttons on my website. I have a Button that could activate function one, function two or function three. However, I want to make it so there is a 60% chance that function one gets called from the ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...

What are some ways to streamline and improve the readability of my if/else if statement?

I've created a Rock Paper Scissors game that runs in the console. It currently uses multiple if/else if statements to compare user input against the computer's selection and determine a winner. The code is quite lengthy and repetitive, so I' ...