0

I'm quite new in coding, so might be an easy question for you all. What exactly should I do if I have this array and want to just show the first letter of every element of it?

var friends = ["John", "Will", "Mike"];

I wanted to do it with substr method but I just want to know how to do it with a string.

2
  • What is the expected output? Commented Apr 25, 2018 at 11:49
  • 1
    This is a question I would give someone learning JavaScript and I would except that person to perform some research to come to a solution. I advise the same for you. hint: loops and substring Commented Apr 25, 2018 at 11:52

5 Answers 5

1

Use Array.map() to iterate the array, take the 1st letter using destructuring, and return it:

const friends = ["John", "Will", "Mike"];
const result = friends.map(([v])=> v);
console.log(result);

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

2 Comments

Thanks, but what does these => operators stand for?
ES6 arrow functions
0

As everyone else is using new fancy ECMAScript6 I'll give the oldschool version of it:

var friends = ["John", "Will", "Mike"];

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

Comments

0

Use loop for that array and access the first character using charAt(0)

var friends = ["John", "Will", "Mike"];
friends.forEach((name)=>{
  console.log(name.charAt(0));
});

charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

Comments

0

Know something about Array.prototype.map

var friends = ["John", "Will", "Mike"];
console.log(friends.map(v=>v[0]))

Comments

0

You can use .map() to create array of first letters like:

let firstLetters = friends.map(s => s[0]);

Demo:

let friends = ["John", "Will", "Mike"];

let firstLetters = friends.map(s => s[0]);

console.log(firstLetters);


Alternatively you can use String's .charAt() method:

let firstLetters = friends.map(s => s.charAt(0));

Demo:

let friends = ["John", "Will", "Mike"];

let firstLetters = friends.map(s => s.charAt(0));

console.log(firstLetters);


Docs:

2 Comments

sweet! and what about showing just the last letter of every element? is it possible to do it with the same .map and/or charAt method?
@Pepdbm7 Yes, just use string.length - 1 as index. For example friends.map(s => s[s.length - 1]); or with charAt() like friends.map(s => s.charAt(s.length - 1);

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.