0

I'm trying to have my function loop through var list and match text that is pasted into a text box in HTML. For instance the only two examples right now in var list, if 'AFCOMMMDL' exists in the pasted text, I want the function to return 'Air Force Commendation Medal'. I would do this, searching the text for all of the abbreviated codes and returning the one right after and pushing it to the empty finalList[] which will eventually be printed. I'm new to Javascript and have searched this all over and can't find an answer. Thank you in advance.

 function sortAwards() {
   //Assign rewards variable whatever content was pasted in text box
   var rewards = document.getElementById("paste").value;

    //Remove spaces from pasted text
    rewards = rewards.replace(/\s/g, '');

    //Empty list to contain all of the matches
    var finalList = [];

    var list = {
       'AFCOMMMDL': 'Air Force Commendation Medal',
        'AFACHIEVMDL': 'Air Force Achievement Medal',
    }

    for (index = 0; index < list.length; index++) {
        if (rewards.includes(index)) {
           rewards.push[index];
        }
    }

    //Test to show result
    document.getElementById('test').innerHTML = finalList;
   };
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    What is `rewards.push[index];` supposed to do? – Jonas Wilms Dec 07 '19 at 18:04
  • Also `list` is not an array, thus it doesn't have a length ... Maybe you want `for(const abbreviation of Object.values(list)) { /*...*/ }` ? – Jonas Wilms Dec 07 '19 at 18:05
  • So I want the result to be added to the finalList. Eventually return all matches to the codes that were pasted. And apologies, yes list is an object not an array. How can I loop through an object, match the keys to the pasted text, and return the keys value? – Kaepora Gaebora Dec 07 '19 at 18:14
  • Are you sure about `innerHTML = finalList` when `finalList` is an array and not HTML (or text)? Don't you want to just replace and get a string -- forget arrays? – trincot Dec 07 '19 at 18:21
  • Why is your function called `sortAwards`, when no sorting is ever happening? – trincot Dec 07 '19 at 18:23

1 Answers1

0

You likely meant this

Filter and Map (you could use reduce, but that is harder to read)

const list = {
  'AFCOMMMDL': 'Air Force Commendation Medal',
  'AFACHIEVMDL': 'Air Force Achievement Medal'
}

function expandAcronyms() {
  //Assign rewards variable whatever content was pasted in text box
  var rewards = this.value;
  var finalList = rewards.split(/\W+/) // split on not words
    .filter(word => list[word])        // return only found words
    .map(word => list[word])           // lookup and return the value
    .join(", ");                       // join with ", "
  document.getElementById('test').innerHTML = finalList;
}

document.getElementById("paste").addEventListener("input",expandAcronyms)

//filter(res => res)
<textarea id="paste"></textarea>
<div id="test"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236