How can I compare input
and Array elements? What I want to do is reading an user’s input and if this input is the same as one of the Arrays elements, it should call for console.log()
. But I can’t find a way to make it work.
Can anyone help?
EDIT: The Github link is provided if you need more information. https://github.com/TheRadioDept/technical-question
EDIT: The way to compare was found, its:
rl.question('Please enter the translation key ', (key) => { if (keys.includes(key)){ console.log(data.map(point=>point.translations.deu.official)); }
Now I want to change it from console.log(data.map(point=>point.translations.deu.official));
to
console.log(data.map(point=>point.translations.key));
. But the output becomes undefined
. Is there a way to fix that?
var keys = ['cym','deu','fra','hrv','ita','jpn','nld','por','rus','spa']; const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Please enter the translation key ', (key) => { if (key.match(/^keys[0]?$/i)){ console.log(data.map(point=>point.translations.deu.official)); } else { console.log("Translation key is not supported. "); } rl.close();
Advertisement
Answer
I see you are matching using regex, you should use when you are dealing with strings. If you have an array containing your answers, to find whether an element is there you have always to iterate over said array.
for (element in array) { // compare against your element }
However, all modern programming language will provide you with a function that does that looping for you. In JavaScript that’s Array.prototype.includes()
Using it in your code
rl.question('Please enter the translation key ', (key) => { if (keys.include(key)){ console.log(data.map(point=>point.translations.deu.official)); }
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes