[英]How to loop through an array to get the first character of each string
I'm working on extracting the first letter of the word to form an acronym. 我正在提取单词的第一个字母以形成首字母缩写词。 I have an array to store all the Capticalized words and what I need to do is to get those Capitalized characters.
我有一个数组来存储所有大写的单词,我需要做的就是获取那些大写的字符。
I used array reduce()
method to get the capital letter. 我使用了数组
reduce()
方法来获取大写字母。 But I would like to get all the acronyms formed by different numbers of the capital letter. 但是,我想获得由不同大小写字母组成的所有首字母缩写词。
var words = ["In", "American", "Broadcast", "Company"];
var output = words.reduce((acronym, word) => {
acronym += word.charAt(0);
return acronym;
}, "");
This will produce an output IABC
, but we know the correct acronym is ABC
, so I am thinking can we get C, BC, ABC, IABC
in an iteration and then get the correct acronym ABC
? 这将产生一个输出
IABC
,但是我们知道正确的首字母缩写是ABC
,所以我想我们可以迭代获得C, BC, ABC, IABC
,然后获得正确的首字母缩写ABC
吗?
To achieve expected result, use below option of reversing array and using reduce with unshift array method 为了获得预期的结果,请使用以下反转数组选项,并使用带有未移位数组的reduce方法
working code sample for reference 工作代码示例以供参考
var words = ["In", "American", "Broadcast", "Company"]; var result = [] var output = words.reverse().reduce((acronym, word, i) => { acronym.unshift(word.charAt(0)) result.push(acronym.join("")) return acronym; }, []); console.log("result", result);
codepen - https://codepen.io/nagasai/pen/voXXYO?editors=1010 codepen- https: //codepen.io/nagasai/pen/voXXYO ? editors = 1010
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.