JSFiddle - React, Tailwind, and code Playground

by soulwire

JavaScript

/**
 * Given a string of text and n-gram size, returns an object containing frequency of n-grams
 */
function nGrams(text, n) {
	const words = text.toLowerCase().split(/\s+/);
  const groups = [];
	for (let i = 0; i <= words.length - n; i++) {
  	groups.push(words.slice(i, i + n).join(' '));
  }
	return groups.reduce((result, text) => {
  	result[text] = (result[text] || 0) + 1;
    return result;
  }, {});
}

console.log(nGrams("The quick fox jumped over the quick fox", 2));
// {the quick: 2, quick fox: 2, fox jumped: 1, jumped over: 1, over the: 1}