How can I extract a specific element from an array by inputting its index position?

I am attempting to find out which teacher is responsible for a particular student based on the classroom they are in. Each teacher corresponds to a specific set of classrooms.

let teachers = ["Arrington", "Kincart", "Alberts", "Pickett"]
let rooms = [
  ["Andy", "Rodolfo", "Lynn", "Talia"],
  ["Al", "Ross", "Jorge", "Dante"],
  ["Nick", "Kim", "Jasmine", "Dorothy"],
  ["Adam", "Grayson", "Aliyah", "Alexa"]
]
let findTeacher = (student) => {
    return rooms.findIndex(row => row.indexOf(student) !== -1)
}

console.log(`The teacher who manages Jorge is ${findTeacher("Jorge")}.`)
console.log(`The teacher who guides Alexa is ${findTeacher("Alexa")}.`)

The current result shows:

The teacher who has Jorge is 1.
The teacher who has Alexa is 3.

I realize that I'm close, but I need assistance in outputting the actual name of the teacher instead of just their index number.

Answer №1

Utilize the array of teachers that you have forgotten to include. By utilizing indexing, you can successfully achieve your desired outcome:

let teachers = ["Smith", "Johnson", "Williams", "Jones"]


let classes = [
  ["Emma", "Liam", "Olivia", "Noah"],
  ["Ava", "Isabella", "James", "Sophia"],
  ["Logan", "Lucas", "Mia", "Ethan"],
  ["Amelia", "Michael", "Charlotte", "Daniel"]
]

let findTeacher = (student) => {
    return teachers[classes.findIndex(row => row.indexOf(student) !== - 1)]
    //             ^ use the located index to reference the teachers array
}


console.log(`The teacher of James is ${findTeacher("James")}.`)
console.log(`The teacher of Amelia is ${findTeacher("Amelia")}.`)

Answer №2

If you need to find the teacher corresponding to a student, you can simply access the teacher at the specified index within the teachers array:

const teachers = ["Arrington", "Kincart", "Alberts", "Pickett"]
const rooms = [
  ["Andy", "Rodolfo", "Lynn", "Talia"],
  ["Al", "Ross", "Jorge", "Dante"],
  ["Nick", "Kim", "Jasmine", "Dorothy"],
  ["Adam", "Grayson", "Aliyah", "Alexa"]
]
const findTeacher = student => teachers[ rooms.findIndex(row => row.includes(student)) ]


console.log(`The teacher of Jorge is ${ findTeacher("Jorge") }.`)
console.log(`The teacher of Alexa is ${ findTeacher("Alexa") }.`)

(By the way: it's recommended to use const over let, especially for arrow functions, and utilize built-in functions like Array.prototype.includes for improved clarity and potentially better performance.)

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

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...

Combining the power of Angular.js and Require.js

As I develop a local app on nw.js using angular.js, I'm starting to question my approach. In my controller, I often find myself writing code like this: .controller('UserSettingsCtrl', function($scope, $mdDialog, $translate) { var fs = ...

Unexplained code snippet: templates.keys() iterating over templates in Webpack - what does it signify?

I'm exploring ways to include html templates in a Webpack bundle using ngTemplate-loader and html-template-loader. While examining code from another project, I came across two lines that achieve this: const templates = require.context(__dirname, true ...

Dealing with object properties that may not always be present in Vue.js template tags

Encountering a fatal error TypeError: Cannot read properties of null (reading 'propThatSometimesDoesNotExist') when utilizing the code below: <template> <div> <img v-if="obj.propThatSometimesDoesNotExist" :src=" ...

The error message "Unable to call mxgraph function during Jest unit testing" occurred during the execution of

My Vue JS Component is utilizing the mxgraph package, which can be found at: https://www.npmjs.com/package/mxgraph The component imports the package like so: import * as mxgraph from 'mxgraph'; const { mxClient, mxStackLayout, mxGraph, ...

You cannot pair Reanimated 2 withSequence using a direct value

Trying to implement withSequence with a direct value as the initial input resulted in crashing the application. animatedValue.value = withSequence(startValue, withTiming(endValue)); Although the following code appeared to be functioning correctly, it did ...

Scrollable container with jQuery draggable functionality

I am currently working on implementing a draggable list that I want to contain within a scrollable div. $( ".draggable" ).draggable(); Here is the fiddle I have created for this: http://jsfiddle.net/YvJhE/660/ However, the issue I am facing is that the ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

Shifting and positioning the card to the center in a React application

I am currently constructing a React page to display prices. To achieve this, I have created a Card element where all the data will be placed and reused. Here is how it appears at the moment: https://i.stack.imgur.com/iOroS.png Please disregard the red b ...

Storing a JavaScript file using C# code snippets

<head runat="server"> <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title> <link href="../../Content/css/layout.css" rel="stylesheet" type="text/css" /> <script type="text/j ...

Is it possible to modify the express static directory path depending on the route being accessed?

I am trying to dynamically change the static path based on the route. Here is an example of what I have tried: const app = express(); const appRouter = express.Router(); const adminRouter = express.Router(); appRouter.use(express.static('/path/to/ap ...

Encountering an issue with Firebase authentication in Next.js: the window object is not defined

Here is some code snippets: import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; import { getAuth } from "firebase/auth"; const firebaseConfig = { //credentials// }; export const ...

Utilizing modal functionality for seamless integration of new data into mui-datatable

When trying to add a new data entry using a modal box, I encountered an issue where the new data was not being added to the datatable. Is there a solution for this problem? Below is the code snippet I used: let id = 0; function createData(name, provider) ...

Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller: public JsonResult GetRights(string ROLE_ID) { var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList(); return Json(re ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

Terminating a client connection in Node.js using socket.io

What is the best way to terminate the socket connection on the client side? I am currently utilizing: socket.io 0.9 node.js 0.10.15 express 3.3.4 For example, when calling localhost/test -- server side var test = io .of('/test') .on(&apos ...

Moving through content on a single page

import React, { Component, useState } from "react"; import { Content, List, ListItem, Left, Right, Icon, Container, Header, Body, Button, Title, } from "native-base"; //Chapter One expor ...

Having trouble with a tslint error in Typescript when creating a reducer

I encountered an error while working with a simple reducer in ngRx, specifically with the on() method. https://i.sstatic.net/9fsvj.png In addition, I came across some errors in the reducer_creator.d.ts file: https://i.sstatic.net/sWvMu.png https://i.ss ...

Transforming a callback function into a Promise: A step-by-step guide

I'm currently utilizing Bluebird promises and attempting to make the following function work with Promisify: var jwt = require('jsonwebtoken'); function _test_encode() { var cert = fs.readFileSync('public.pub'); return j ...

What is the secret behind Redactor JS's ability to display properly indented code snippets?

If you take a look at the Redactor JS demo and click on the button to show the HTML source code of the displayed content... ...you will notice that the code is properly indented: Most rich text editors or wysiwyg editors typically display code in a singl ...