I'm learning JavaScript for the first time and I would like to know why my code doesn't work. I have Python/Django knowledges.
I have to create a list of names and I have to display only firstnames which begins by 'B' letter.
var listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
for (var i in listNames) {
if (i.substr(0, 1) === 'B') {
console.log(i);
}
}
But this code doesn't display something.
You need to use listNames[i]
as i
gives you the index
of array listNames
. Then use charAt(0)
to the value of the array to check for the first character as B
.
var listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
for (var i in listNames) {
if (listNames[i].charAt(0) === 'B') {
console.log(listNames[i]);
}
}
If you want to use the values of array that start with B
further in your code as a separate array then use filter()
:
var listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
var res = listNames.filter(item => item.charAt(0) === 'B');
console.log(res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With