This function will be called when user clicks on the button
Reading file text
Calling function findFrequencyOfWords(string) to find frequency of words
constfetchData=async()=>{try{setShowButton(false);constdataBuffer=awaitfetch(testData);constdata=awaitdataBuffer.text();findFrequencyOfWords(data.toLowerCase());}catch(error){console.log("Something went wrong while fetching data");console.log(error);}};
Find Frequency function
This function will be called inside the fetchData()
Step 1 replacing all the characters like ! . ?
Step 2 converting string to array
Step 3 finding frequency of words and storing them in freqMap object
Step 4 converting object into array
Step 5 sorting frequency in descending order
Step 6 removing the empty character
Step 7 Creating two arrays of wordsArray and frequencyArray for charts library
Step 8 Storing in the state
constfindFrequencyOfWords=(string)=>{// Replacing characters and splitting into arrayletwords=string.replace(/[,.!-?]+/g,"").split(/\s/);letfreqMap={};letwordFrequency=[];// Finding frequency of wordswords.forEach((word)=>{if(!freqMap[word]){freqMap[word]=0;}freqMap[word]+=1;});// Converting object into arrayObject.keys(freqMap).forEach((word)=>{letwordObject={word: "",frequency: null};wordObject.word=word;wordObject.frequency=freqMap[word];wordFrequency.push(wordObject);});// Sorting wordFrequency array in descending orderwordFrequency.sort((a,b)=>b.frequency-a.frequency);// Removing the empty character from the arrayif(wordFrequency[0].word===""){wordFrequency.shift();}// making two array words and frequenciesletwordsArray=[];letfrequencyArray=[];for(leti=0;i<20;i++){wordsArray.push(wordFrequency[i].word);frequencyArray.push(wordFrequency[i].frequency);}setFrequencies(frequencyArray);setWords(wordsArray);};