I'm trying to return the teacher's name based on what classroom the students name is in. teacher[0] is responsible for rooms[0] and teacher[1] is responsible for rooms[1] and so on.
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 whichTeacher = (student) => {
return rooms.findIndex(row => row.indexOf(student) !== - 1)
}
console.log(`The teacher who has Jorge is ${whichTeacher("Jorge")}.`)
console.log(`The teacher who has Alexa is ${whichTeacher("Alexa")}.`)
the current output is
The teacher who has Jorge is 1.
The teacher who has Alexa is 3.
so I know im close but I cant figure out how to output the teachers name instead of its index number.
CodePudding user response:
You forgot to use your teachers array. By indexing it you can achieve what you want:
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 whichTeacher = (student) => {
return teachers[rooms.findIndex(row => row.indexOf(student) !== - 1)]
// ^ use the found index to index the teachers array
}
console.log(`The teacher who has Jorge is ${whichTeacher("Jorge")}.`)
console.log(`The teacher who has Alexa is ${whichTeacher("Alexa")}.`)
CodePudding user response:
You can just get the teacher at this index of 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 whichTeacher = student => teachers[ rooms.findIndex(row => row.includes(student)) ]
console.log(`The teacher who has Jorge is ${ whichTeacher("Jorge") }.`)
console.log(`The teacher who has Alexa is ${ whichTeacher("Alexa") }.`)
(btw : prefer using const
instead of let
whenever its possible (even more for arrow functions) and use the built-ins when you can (like Array.prototype.includes
instead of array.indexOf(...) != -1
) for clarity and sometimes for performances)