Started with what I thought was a simple idea for a class activity for our JavaScript unit, but falling foul best way to read a JavaScript 2D array based on a user input.
How can I get it to look up the users entry in the first index of the array and output the value in the second index? I need to tell it at some point which index to read and which to output, via similar syntax to [0][1] I imagine, but trial and error is getting me far.
Perhaps there is a better way??
Here is what I have so far, which just outputs the first array entry in its entirety - "A","Angelic"
var firstNames = [
["A","Angelic"],
["B","Blustery"],
........
["Y","Cheery"],
["Z","Dancy"]
];
var firstInitial = window.prompt("What is the first letter of your first name: ").toUpperCase();
let elfFirstName = firstNames.find(firstSearch);
function firstSearch(firstInitial) {
return firstInitial;
}
window.alert("Your Elf Name is " elfFirstName);
</script>```
Thanks
CodePudding user response:
You could take an object with the initials as keys.
const
firstNames = {
A: "Angelic",
B: "Blustery",
Y: "Cheery",
Z: "Dancy"
},
firstInitial = window.prompt("What is the first letter of your first name: ")[0].toUpperCase(),
elfFirstName = firstNames[firstInitial];
console.log("Your Elf Name is " elfFirstName);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You do not use find right. It needs to look at the first index of your array that is passed in.
function firstSearch(item) {
return item[0] === firstInitial;
}
So
var firstNames = [
["A", "Angelic"],
["B", "Blustery"],
["Y", "Cheery"],
["Z", "Dancy"]
];
var firstInitial = window.prompt("What is the first letter of your first name: ").toUpperCase();
const elfFirstName = firstNames.find(firstSearch)[1];
function firstSearch(item) {
return item[0] === firstInitial;
}
window.alert("Your Elf Name is " elfFirstName);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Better solution as I pointed out in the comments is using an array
var firstNames = {
A: "Angelic",
B: "Blustery",
Y: "Cheery",
Z: "Dancy"
};
var firstInitial = window.prompt("What is the first letter of your first name: ").toUpperCase();
const elfFirstName = firstNames[firstInitial];
window.alert("Your Elf Name is " elfFirstName);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>