Create a function that takes an array as input and retrieves the element in the array that corresponds to the specified question

To solve this problem, I'm tasked with creating a function called findAnswers(answers, questions). The function should return the item in the array that corresponds to the given question. If none of the student's answers match the question, the function should return undefined. In the case where more than one student's answer matches the question, the function should return the first one in the array.

Here is an example output:

findAnswer(answers, "True or False: Prostaglandins can only constrict blood vessels."); /*=>
  {
    question: 'True or False: Prostaglandins can only constrict blood vessels.',
    response: 'True',
    isCorrect: false,
    isEssayQuestion: false
  }
*/

Given the array:

let answers = [
  {
    question: 'What is the phase where chromosomes line up in mitosis?',
    response: 'Metaphase',
    isCorrect: true,
    isEssayQuestion: false
  },
  {
    question: 'What anatomical structure connects the stomach to the mouth?',
    response: 'Esophagus',
    isCorrect: true,
    isEssayQuestion: false
  },
  {
    question: 'What are lysosomes?',
    response: 'A lysosome is a membrane-bound organelle found in many animal cells. They are spherical vesicles that contain hydrolytic enzymes that can break down many kinds of biomolecules.',
    isCorrect: true,
    isEssayQuestion: true
  },
  {
    question: 'True or False: Prostaglandins can only constrict blood vessels.',
    response: 'True',
    isCorrect: false,
    isEssayQuestion: false
  }
];

Here is what I've attempted so far:

function findAnswer(answers, question) {
  let result = {};
  
  for (let i = 0; i < answers.length; i++) {
    let studentAnswers = answers[i];
    if (studentAnswers === answers) {
      result[answers[i].question]
    }
  }
  return result;
}

I'm aware that the current code is not optimal, and I'm struggling with returning an array of matching responses.

Answer №1

If you need to locate an element in an array that meets a certain condition, you can utilize the .find method. This method will give back undefined if no match is detected:

const searchForAnswer = (answers, question) => answers.find(
  answer => answer.question === question
);

let answers = [
  {
    question: 'What is the phase where chromosomes line up in mitosis?',
    response: 'Metaphase',
    isCorrect: true,
    isEssayQuestion: false
  },
  {
    question: 'What anatomical structure connects the stomach to the mouth?',
    response: 'Esophagus',
    isCorrect: true,
    isEssayQuestion: false
  },
  {
    question: 'What are lysosomes?',
    response: 'A lysosome is a membrane-bound organelle found in many animal cells. They are spherical vesicles that contain hydrolytic enzymes that can break down many kinds of biomolecules.',
    isCorrect: true,
    isEssayQuestion: true
  },
  {
    question: 'True or False: Prostaglandins can only constrict blood vessels.',
    response: 'True',
    isCorrect: false,
    isEssayQuestion: false
  }
];
const searchForAnswer = (answers, question) => answers.find(
  answer => answer.question === question
);

console.log(searchForAnswer(answers, "True or False: Prostaglandins can only constrict blood vessels."));

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

Inquiring about a particular key-value in a buffer variable in GoLang

Within my code, I have a variable buffer that holds a collection of key-value pairs in an array format like this: [{"Key":"area1", "Record": {"name":"belfast","type":"surburban","v ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

Does the ngIf directive cause a re-evaluation of variables when used with one-time-binding in AngularJS?

I recently had a colleague at work demonstrate a peculiar quirk with one-time binding in Angular. Scenario: Imagine having an element with text being bound using one-time binding inside a block that is conditional on ng-if. If you update the value, say b ...

How to Troubleshoot VueJS Component Render Issues After Importing/Calling Components

In one of my projects, I successfully implemented a file uploader component using import and component statements. import fileUploader from '../common/FileUploader.vue'; Vue.component('file-uploader', fileUploader); This implementation ...

The Html is not having JavaScript executed before it

Within my header, there is a script that is making a call to a web API in order to populate a view model. The script is as follows: @using GigHub.Controllers @using GigHub.ViewModel @model GigHub.ViewModel.ProjectsViewModel @{ ViewBag.Title = "Projects"; ...

Transitioning from Three.js's CanvasRenderer to WebGLRenderer is a significant upgrade

Can a Three.js script created with CanvasRenderer be easily converted to use WebGLRenderer instead, and if yes, what is the process for doing so? ...

The conditional logic in AngularJS is not functioning as expected

https://i.sstatic.net/RvqYQ.pngMy code seems to have an issue with the if/else statement. I am checking the value of data.success which should contain either true or false. However, when I use (data.success === true) in the if statement, the else block e ...

How to specify a unique body parser for a specific route in Express

Currently, I am utilizing express version 4 in my project. Within my server.js file, I have integrated the express.json() middleware to handle JSON data. require('dotenv').config(); const express = require('express'); const cors = requi ...

Stop processing the current websocket connection once a new websocket request is received

Currently, I am utilizing the npm ws module (or its wrapper named isomorphic-ws) for establishing a websocket connection. NPM Module: isomorphic-ws This setup allows me to retrieve an array of data from a websocket++ server situated on the same local mac ...

Conditions in Controller Made Easy with AngularJS

I have recently started working on implementing a notifications feature. The service will involve making a GET request to a specific URL which will then return an array of notifications. Within the controller, I am in the process of setting up a variable ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...

Measuring data entries within JSON array utilizing JavaScript and Postman

A specific component is returning two records: { "value": [ { "ID": 5, "Pupil": 1900031265, "Offer": false, }, { "ID": 8, "Pupil": 1900035302, "Offer": false, "OfferDetail": "" } ] } My task i ...

Encountering an error when utilizing the ForEach method

Encountering a problem with using forEach: I am receiving an error message stating "unhandledRejection: TypeError: data.forEach is not a function" Here is the solution I attempted: I converted the data into JSON format before using forEach const data = JS ...

Changing the height of tablerows in Material UI v5: A step-by-step guide

I am attempting to adjust the height of the rows in this material-ui code example. import * as React from "react"; import { styled } from "@mui/material/styles"; import Table from "@mui/material/Table"; import ...

Adding a class to the body depending on the tag or href that was clicked on the previous page

Currently, I am working on two pages - the "Home-Page" and the "Landing-Page". My goal is to customize the content of the "Landing-Page" based on the button clicked on the previous page (which happens to be the "Home-Page"). Initially, I tried using ancho ...

Creating an Observable Collection in Angular using AngularFire2 Firestore

I am currently using material 2 and attempting to develop data tables with pagination and sorting. In order to achieve this, I require my collections to be observable. However, I believe that I might be incorrectly populating or initializing the arrays in ...

Running the Express service and Angular 6 app concurrently

Currently, I am in the process of developing a CRUD application using Angular6 with MSSQL. I have managed to retrieve data from my local database and set up the necessary routes, but I am encountering difficulties when it comes to displaying the data on th ...

Implementing a JQuery modal with backend coding

I have encountered a problem in my ASP.NET code-behind where I am trying to incorporate a modal popup. Despite my efforts, I have not been able to successfully implement it. Do you have any suggestions on how I should proceed with this process? <scrip ...

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...

What steps should I take to make the initiallyHidden attribute in FusionCharts work properly?

I am encountering an issue with my chart that is reloaded periodically. I want to make sure that the series hidden by the user (by clicking on their legend names) remain hidden even after reloading. I attempted to set the series initiallyHidden attribute t ...