JavaScript: Extract first letter of every string in array?

三世轮回 提交于 2020-06-13 09:29:52

问题


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.


回答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);



回答2:


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]);
}



回答3:


You can use map() and charAt():

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

friends = friends.map(i=> i.charAt(0))

console.log(friends);



回答4:


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.




回答5:


Know something about Array.prototype.map

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



回答6:


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:

  • Array.prototype.map()
  • String.prototype.charAt()


来源:https://stackoverflow.com/questions/50021569/javascript-extract-first-letter-of-every-string-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!