0

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?

9
  • 3
    Do you have a different array that contains acronyms you consider "correct"? Your code has no reason to know that "ABC" is correct but "IABC" is not. Commented Jul 25, 2019 at 20:32
  • 1
    Why not consider also "IBC", "IAC", "IAB", "IA", "IB", "IC"? Commented Jul 25, 2019 at 20:33
  • @CalIrvine for example, in a text file, I am able to get "ABC" as an acronym, then I need to find its explanation. And I extract this array to extract the first letter of each word in order to match ABC. So I'm thinking a way to extract a pair of acronyms and then compare Commented Jul 25, 2019 at 20:41
  • reverse array and use reduce var output = words.reverse().reduce((acronym, word) => { acronym += word.charAt(0); return acronym; }, ""); Commented Jul 25, 2019 at 20:42
  • 1
    As far as I understand, you want to ignore prepositions, pronouns, conjunctions or to explain what I mean is that you want to ignore some words to be a part of your acronym? if that's the case, I think you would need to have a dictionary for those words and ignore them at first place by checking if your dictionary has those words then ignore them. sorry if I got you wrong Commented Jul 25, 2019 at 23:37

1 Answer 1

1

To achieve expected result, use below option of reversing array and using reduce with unshift array method

  1. Reverse array using .reverse()
  2. Loop using reduce and add first character to beginning on every iteration
  3. Join on every iteration and push to result array

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

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

Comments

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.