Search code examples
javascriptarraysloops

Getting the first characters of each string in an array in Javascript


let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

let secretMessage = animals.map(function(animal) {
     for(animal = 0; animal <= animals.length-1; animal++) {
            return animals[animal].charAt(animal);
     }
});

console.log(secretMessage.join(''));

Hi, thru this piece of code i want to output the string HelloWorld, which is formed by the first characters of each string/element in the animals array. However, the output is instead HHHHHHHHHH. I don't know if the for loop is the problem here?

Could someone please tell me why the code produces such an output and how i can modify it in order for the desired result to be returned successfully?

I'm just a novice for now & that's why your help will play a tremendous part in my growth as a programmer. Thanks in advance!


Solution

  • Array.prototype.map() is a for loop in and of itself.

    Try:

    // Animals.
    const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog']
        
    // Secret Message.
    const secretMessage = animals.map((animal) => animal[0]).join('')
        
    // Log.
    console.log(secretMessage) // "HelloWorld"

    Or alternatively:

    // Animals.
    const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog']
    
    // Secret Message.
    const secretMessage = animals.reduce((accumulator, animal) => accumulator + animal[0], '')
    
    // Log.
    console.log(secretMessage) // "HelloWorld"