Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over array using charAt to get first letter of each value in javascript

I am new to JS and am trying to understand chartAt. I created a problem where I want to go through an array and pull the first character of each value from my array using charAt. I'm a bit stuck with my code.

var myArray = ['adam', 'bianca', 'cat', 'dennis'];
var myFunc = function (letter) {
    for (var i = 0; i < letter.length; i += 1) {
        letter.charAt(0);
        console.log(letter.charAt(0));
    }
}
like image 884
jstone Avatar asked Oct 06 '26 22:10

jstone


2 Answers

In your iteration loop, letter is the array passed to the function myFunc(). You need to access its elements, which you're iterating via i. Use letter[i].charAt(0) instead of letter.charAt(0)

var myArray = ['adam', 'bianca', 'cat', 'dennis'];
var myFunc = function (letter) {
    for (var i = 0; i < letter.length; i += 1) {
        // Use the index i here
        console.log(letter[i].charAt(0));
    }
}

// Call your function, passing in the array you defined:
myFunc(myArray);
// a
// b
// c
// d

So your understanding of String.prototype.charAt() is correct, but the loop iteration was faulty.

like image 180
Michael Berkowski Avatar answered Oct 09 '26 13:10

Michael Berkowski


If what you want to do is go through each element in the array and get the first letter, you need to iterate over the array, not the word (which you call letter in your solution. So you would have something like this:

for( var i=0; i<myArray.length; i++ ) {
    console.log( myArray[i].charAt(0) );
}

Or:

myArray.forEach( function(word){
    console.log( word.charAt(0) );
});

Also, you're creating a function (myFunc), but then you're never actually invoking it.

like image 27
Ethan Brown Avatar answered Oct 09 '26 12:10

Ethan Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!