Essex
Essex

Reputation: 6128

Learning JavaScript : display all firstnames with B as first letter

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.

Upvotes: 6

Views: 307

Answers (5)

zeljko_a
zeljko_a

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

Asons
Asons

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

Iurii Drozdov
Iurii Drozdov

Reputation: 1755

Try this:

listNames.forEach((el) => {if (el.charAt(0) == 'B') console.log(el)});

Upvotes: 2

Mr. Roshan
Mr. Roshan

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

Ankit Agarwal
Ankit Agarwal

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

Related Questions