Compare two arrays and show number of matches in a percentage value I wrote this to be able to compare two different arrays to figure out how many words were in common as a percentage value.

The use case is that I have array a which is a list of the most commonly known and used words in a language (normally something like 2000 different words).
In array b I have the text.

The end result is the percentage usage of commonly used words as a means to figure out total readability of the text.

Note:
The intersect_array function is used elsewhere in the full fledged application.

The full functioning CodePen can be viewed here: http://codepen.io/MarkBuskbjerg/pen/rWWRbX?editors=0010

The JS goes like this:

tinymce.init({
  selector: '#myTextArea',
  height: 300,
  setup: function(ed) {
    ed.on('keyup', run);
  },
  init_instance_callback: "run"
});

// helper function that matches two arrays with each other
function intersect_arrays(a, b) {
  var sorted_a = a.concat().sort();
  var sorted_b = b.concat().sort();
  var common = [];
  var a_i = 0;
  var b_i = 0;

  while (a_i &lt; a.length &amp;&amp; b_i &lt; b.length) {
    if (sorted_a[a_i] === sorted_b[b_i]) {
      common.push(sorted_a[a_i]);
      a_i++;
      b_i++;
    } else if (sorted_a[a_i] &lt; sorted_b[b_i]) {
      a_i++;
    } else {
      b_i++;
    }
  }
  return common;
}

// simple addition function
function add(a, b) {
  return a + b;
}

function run(inst) {
  var sum;
  var percentageUsage;
  var words = ["store", "javascript", "hammertime"];
  var result = {};
  var text = tinyMCE.get('myTextArea').getContent({
      format: 'text'
  })
    .replace(/&lt;([^&gt;]+)&gt;|[\.\+\?,\(\)"'\-\!\;\:]/ig, "")
    .toLowerCase()
    .split(/[\s]/)
    .filter(Boolean);
  var textLength = text.length;
  var match = intersect_arrays(text, words);

  for (var y = 0; y &lt; match.length; y++) {
    for (var i = 0; i &lt; text.length; ++i) {
       if(text[i] === match[y]) {
         if (!result[text[i]])
            result[text[i]] = 0;
            ++result[text[i]];
       }
    }
  }

 sum = Object
    .values(result)
    .reduce(add, 0);

   percentageUsage = textLength / sum;

   document.getElementById('totalWords').innerHTML = textLength;
   document.getElementById('totalPercentage').innerHTML = percentageUsage;
}


Any ideas as to how I can handle the code more effective, easier or just in a more beautiful way is more than welcome. I'm quite new at JS so still wanna learn a lot about best practice and stuff.
I'm assuming you have already broken your text down into its individual words and stripped the punctuation marks, etc, in your text array?

If so, the percentage of words from the given text array that match your word-list should be pretty easy to find.

Something along the lines of:

function matchPerc(wordList, text){
  var matches = text.filter((word)=&gt;{return wordList.includes(word)}).length
  return (matches / text.length * 100).toFixed(2) + '%'
}