How to determine the frequency of a specific word in a sentence using Angular 5

I need help finding a solution to count how many times a word appears in sentences.

Input:
k = 2
keywords = ["anacell", "cetracular", "betacellular"]
reviews = [
  "Anacell provides the best services in the city",
  "betacellular has awesome services",
  "Best services provided by anacell, everyone should use anacell",
]

Output:
["anacell", "betacellular"]

Explanation:
"anacell" appears in 2 reviews and "betacellular" only appears in 1 review.

Input:
k = 2
keywords = ["anacell", "betacellular", "cetracular", "deltacellular", "eurocell"]
reviews = [
  "I love anacell Best services; Best services provided by anacell",
  "betacellular has great services",
  "deltacellular provides much better services than betacellular",
  "cetracular is worse than anacell",
  "Betacellular is better than deltacellular.",
]

Output:
["betacellular", "anacell"]

Explanation:
"betacellular" appears in 3 reviews. "anacell" and "deltacellular" appear in 2 reviews, but "anacell" comes first alphabetically.

Using the keywords provided, I want to determine their frequencies in the reviews array and display the most frequently occurring keyword.

Answer №1

analyzeKeywords(keywords: string[], reviews: string[]) => {
    let outcome = [];

    keywords.forEach(keyword => {
        let info = {};
        info.keyword = keyword;
        info.review_total = 0;

        reviews.forEach(review => {
            if (review.toLowerCase().includes(keyword.toLowerCase())) {
                info.review_total += 1;
            }
        })

        outcome.push(info);
    })

    return outcome;
}

Returns an Array of Objects containing relevant data.

https://i.stack.imgur.com/i9uoM.png

Answer №2

Check out the following code snippet to count how many times keywords appear:

let occurrencesMap:any
this.keywords.forEach((keyword)=>
{
  let temp=0;
 this.reviews.forEach((review)=>{
   if(review.indexOf(keyword)>-1){
     temp++
    }
 });
  occurrencesMap[keyword]=temp
})

console.log(occurrencesMap['anacell'])

Answer №3

const searchWords = ["anacell", "cetracular", "betacellular"];
const customerReviews = [
    "Anacell provides the best services in the city",
    "betacellular has awesome services",
    "Best services provided by anacell, everyone should use anacell",
];

let matchedKeywords = [];
for (const word of searchWords)
    for (const review of customerReviews) {
        const lowerCaseReview = review.toLowerCase();
        const lowerCaseWord = word.toLowerCase();
        if (matchedKeywords.indexOf(lowerCaseWord) < 0 && lowerCaseReview.indexOf(lowerCaseWord) >= 0)
            matchedKeywords.push(word);
    }
console.log(matchedKeywords);

Answer №4

Integrated the jamesmallred function to enhance sorting and splice operations.

countKeywords(keywords: string[], reviews: string[]) => {
    let result = [];

    keywords.forEach(key => {
        let data = {};
        data.keyword = key;
        data.count = 0;

        reviews.forEach(review => {
            if (review.toLowerCase().includes(key.toLowerCase())) {
                data.count += 1;
            }
        })

        result.push(data);
    })

    return result;
}

//sorting 

 result.sort((a,b) => {
            if(b.keyword === a.keyword) {
                return a.keyword.localeCompare(b.keyword); // sort alphabetically if equal
            }
            else {
                return b.keyword - a.keyword // sort from highest to lowest 
            }

        });
        
        
//splice based on the input

result.splice(0,k);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to properly pass parameters?

const root = { user: (id) => { console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id))) return storage.select("users", id.id) } } Struggling to correctly pass the parameter ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Setting a default action for an Ext.Ajax.request error situation

In my application, I frequently make ajax requests using the Ext.Ajax.request method. Often, I find myself skipping error handling for failed requests due to time constraints or lack of interest in implementing fancy error handling. As a result, my code us ...

Node.js encountered an error: Module 'mongoose' not found

C:\Users\Alexa\Desktop\musicapp\Bots\Soul Bot>node bot.js Node.js Error: Missing module 'mongoose' at Function._resolveFilename (module.js:334:11) at Function._load (module.js:279:25) at Module.requir ...

typescript function intersection types

Encountering challenges with TypeScript, I came across the following simple example: type g = 1 & 2 // never type h = ((x: 1) => 0) & ((x: 2) => 0) // why h not never type i = ((x: 1 & 2) => 0)// why x not never The puzzling part is w ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...

Retrieving the status of a checkbox using Angular's field binding feature

While using Angular 5.1.1, I am facing an issue where a function is not called correctly when a checkbox changes. This problem seems to occur specifically with the checkbox input type, as it always sends the value "on" to the function even when the checkbo ...

Tips for updating the filename in a file input using AngularJS

Is it possible to dynamically change the name of a chosen file? For instance, if I select a file with the name "img1", can it be automatically changed to a different dynamic name upon selection? <input type="file" fd-input/> ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

"Frustrating issue with Firebase-admin dependency farmhash-modern resulting in webassembly error

Facing an issue while setting up firebase-admin SDK on my nextjs + TS project. Every time I try to call a SDK function, I encounter a webAssembly error. Specifically, when trying to configure a middleware for the server-side API and calling the verifyIdTok ...

Adding a refresh feature to ui-sref in markup

Is there a way to include the reload option in a ui-sref markup without using the javascript function directly? <a ui-sref="app.editPost({new:true}, {reload:true})">new post</a> I've tried this approach, but it doesn't seem to be wo ...

Tips for altering the class of an HTML button dynamically when it's clicked during runtime

I currently have a set of buttons in my HTML page: <button id="button1" onclick="myFunction()" class="buttonClassA"></button> <button id="button2" onclick="myFunction()" class="buttonClassA"></button> <button id="button3" onclic ...

Stop images from appearing transparent when placed inside a transparent div

My issue is clearly visible in this image: The div element is transparent and affecting the images inside it. Below is my HTML code: <div id="cselect" style="position: absolute; top: 99px; left: 37px; display: block;"> <div class="cnvptr"> ...

Access the value retrieved from a form on the previous page using PHP

I'm struggling with extracting values from radio buttons on a previous page. Currently, my HTML and PHP code works fine with the search bar, which is the first form below. However, I'd like to add radio button filters below the search bar. <s ...

Unable to access the values of the object within the form

I am encountering an issue where I cannot retrieve object values in the form for editing/updating. The specific error message is as follows: ERROR TypeError: Cannot read properties of undefined (reading 'productName') at UpdateProductComponen ...

Troubleshooting problem with Ajax Calendar Extender

I have a text box where I need to save the chosen date from a calendar. To achieve this, I am using an AJAX calendar extender and setting the target control property to the textbox ID. However, when I click on a button on the same page, I lose the selected ...

What is the best way to delay a method in vue.js?

In the tab element called competences, there is an input field with the reference search. <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a @click="competencesTabClick" aria-controls="Company" aria-sel ...

Utilizing React JS to call a static function within another static function when an HTML button is clicked

Can you please analyze the following code snippet: var ResultComponent = React.createClass({ getInitialState: function () { // … Some initial state setup ……. }, handleClick: function(event) { // … Handling click event logic …… // Including ...

Yeoman Error: Issue with 'mkdir' in Javascript Execution

Currently, I am in the process of setting up a Meanjs instance using a Yeoman generator. However, when I execute 'sudo yo meanjs', everything goes smoothly until an issue arises while attempting to create a directory and it fails. Any insights on ...

"Utilizing AngulaJS to apply a class to the parent element when a radio button is

I'm wondering how I can assign a class to the parent div of each radio button in a group? You can find the code below and view the corresponding JSFiddle here. Here is the HTML: <div class="bd"> <input type="radio" ng-model="value" val ...