JSFiddle - React, Tailwind, and code Playground

by karan shah

HTML

<input type="submit" id="byBtn" value="GetLowestValue" onclick="getValue()"/>
<span id="result"></span>

JavaScript

function getValue(){
    
    var projects = ["foo", "bar", "a"];
    var sentence = "after a foo, bar and foobar, we all went to a bar";
    var countOccurence = getLowestE(projects,sentence);
    document.getElementById("result").innerHTML = JSON.stringify(countOccurence);
}

//Check for each word if it exists in the sentence by looping 
//throug the split array
//complexity O(m*n)
function getLowestE(projects,sentence){
	//split the sentence
    var sent = sentence.split(" ");
    var res = {};
   	for(var i=0;i<projects.length;i++){
   		var temp = projects[i];
   		var count =1;
   		for(var j=0;j<sent.length;j++){
   			var tempSent = sent[j];
            //remove any special characters
   			tempSent = tempSent.replace(/[^\w\s]/gi, '');
   			if(temp ==tempSent){
   				res[temp]=count++;
   			}
   		}
   	}
    return res;
}