Reputation: 11
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_
Upvotes: 0
Views: 100
Reputation: 2947
write "firstLetter" function and code will be:
const firstLetter = (word) => word[0]
const result = animals.map(firstLetter);
Upvotes: 0
Reputation: 45800
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);
Upvotes: 0
Reputation: 43880
.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));
Upvotes: 0
Reputation: 453
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.
Upvotes: 0
Reputation: 114
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]);
Upvotes: 1
Reputation: 33726
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; }
Upvotes: 3