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. 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
?
To achieve expected result, use below option of reversing array and using reduce with unshift array method
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.