Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning JavaScript : display all firstnames with B as first letter

Tags:

javascript

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.

Objective :

I have to create a list of names and I have to display only firstnames which begins by 'B' letter.

My script :

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.

like image 440
Essex Avatar asked Jun 29 '18 12:06

Essex


1 Answers

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);
like image 85
Ankit Agarwal Avatar answered Sep 21 '22 10:09

Ankit Agarwal