curious
curious

Reputation: 11

JavaScript: how to return the first letter of each word in a string

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

Answers (6)

Sergio Belevskij
Sergio Belevskij

Reputation: 2947

write "firstLetter" function and code will be:

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

Upvotes: 0

Brian Adams
Brian Adams

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

zer00ne
zer00ne

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

Vappor Washmade
Vappor Washmade

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

coder_mz
coder_mz

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

Ele
Ele

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

Related Questions