0

I have this const:

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

and I'm trying to return the first letter of each word. What I have:

const firstLetter = animals.map(animal => {
return_
1
  • 2
    There seems to be missing code here? Commented Mar 17, 2019 at 2:13

6 Answers 6

3

Within the handler of the function map destructure the string for getting the first letter and use it as a result for each index.

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
const result = animals.map(([letter]) => letter);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

1

Do you want to return the first letter of each word of an array (question says 'string').

You're almost there! You could do:

animals.map(a => a[0]);

2 Comments

Yes, it was array, sorry xD
I was typing a letter wrong (lmao), but it ended up working, thank you!
0

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

const firstLetter = [];
for(var i = 0; i < animals.length; i++) {
  firstLetter.push(animals[i][0]);
}
console.log(firstLetter);

If the animals[i][0] doesn't work, you can always use animals[i].charAt(0). My solution is a more basic solution, but it is better because it doesn't use built-in functions.

1 Comment

That could work, yeah, but I have to use .map in this exercise
0

.map() the animals Array. On each word .split('') it into letters and then .shift() to get the first letter.


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

let greeting = animals.map(animal => animal.split('').shift());

console.log(JSON.stringify(greeting));

Comments

0

Use map to get the first letter of each word and use join to combine them into a string:

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

const firstLetters = animals.map(a => a[0]).join('');

console.log(firstLetters);

Comments

0

write "firstLetter" function and code will be:

const firstLetter = (word) => word[0]
const result = animals.map(firstLetter);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.