Reputation: 6128
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.
Upvotes: 6
Views: 307
Reputation: 4165
Use the for...of loop to loop over arrays.
const listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
for (const name of listNames) {
if (name[0] === "B") {
console.log(name);
}
}
Upvotes: 1
Reputation: 87191
You should use forEach
, not for...in
as it's for iterate objects
And the i.substr(0, 1) === 'B'
could be replaced with i.startsWith('B')
var listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
listNames.forEach( i => {
if (i.startsWith('B')) {
console.log(i);
}
})
Or for...of
var listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
for (i of listNames) {
if (i.startsWith('B')) {
console.log(i);
}
}
Yet another option could be to use filter()
and reduce the original array into a new.
var listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
var new_listNames = listNames.filter( i => i.startsWith('B') )
console.log(new_listNames);
Upvotes: 5
Reputation: 1755
Try this:
listNames.forEach((el) => {if (el.charAt(0) == 'B') console.log(el)});
Upvotes: 2
Reputation: 1805
Try this
var listNames = ['Paul', 'Bruno', 'Arthur', 'Bert', 'José']
for (var i of listNames) {
if (i.substr(0, 1) === 'B') {
console.log(i);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 30739
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);
Upvotes: 8