Algorithm for searching and calculating with multiple words (Angular/Javascript)

As I work on loading a JSON file from the database containing two fields - words and grade, I face a challenge. Each word in the file is assigned a grade, for example, "true" has a grade of 1 while "lie" has a grade of -1. My goal is to take input from a text field, grade it based on the values from the JSON file, and then calculate a score by summing up the grades. However, I am struggling to find an efficient way to achieve this. It seems that words not found in the JSON file are not being included in the calculation.

I have attempted methods like string.search() and array searches, but they proved to be too complicated and did not provide the desired results. While looking for online solutions, I realized that no one has implemented anything similar that I could emulate.

JSON

[
  {"word":"true","grade":1},
  {"word":"hate","grade":-1},
  {"word":"dog","grade":0.8},
  {"word":"cat","grade":-0.8}      
]

String

"Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend".

Answer №1

One approach would be to transform your JSON data into a searchable map structure, with the word as the key and the grade as the value:

var json = [
  {"word":"true","grade":1},
  {"word":"hate","grade":-1},
  {"word":"dog","grade":0.8},
  {"word":"cat","grade":-0.8}      
  ];

var map = json.reduce(function(p,c){
    p.set(c.word.toLowerCase(),c.grade);
  return p;
}, new Map());

console.log(...map);

Afterwards, you can split the input string and calculate the total score using the reduce method:

var json = [
      {"word":"true","grade":1},
      {"word":"hate","grade":-1},
      {"word":"dog","grade":0.8},
      {"word":"cat","grade":-0.8}      
      ];

    var map = json.reduce(function(p,c){
        p.set(c.word.toLowerCase(),c.grade);
      return p;
    }, new Map());

var input = "Dogs are wonderful but i prefer cats cats i can not lie although dog is a true friend";

var score = input.split(' ').reduce(function(p,c){
    var wordScore = map.get(c.toLowerCase()) || 0;
    return p + wordScore;
},0);

console.log(score);

Keep in mind that punctuation has been removed from the input text manually in the code above.

Additionally, remember that "cats" and "cat" are considered different words in this context, so some words may not be found!

Answer №2

Before diving into the solution, let's consider the algorithm at play here. There are two possible approaches:

  1. Iterate through the input string for each word in your JSON and count its occurrences.
  2. Compare every word in the input string with the contents of the JSON.

Given that the length of the JSON is likely shorter than the potential input string, option 2 seems like a more efficient choice.

If you decide to go with option 2, the first step is to separate the input string into individual words and store them in an array.

You can achieve this by utilizing the mystring.split(" ") method. While this method may not account for punctuation marks, you can address this issue accordingly.

Next, introduce a counter field for each entry in your JSON to track the number of times it appears in the input string.

Finally, calculate the sum of the product of these counters and the corresponding weights assigned to each entry in the JSON.

Answer №3

console.log((function(rules, text) {
  var totalScore = 0;
  Array.prototype.forEach.call(rules, function(rule) {
    var matchResult = text.match(rule.regexp);
    
    if (matchResult) {
      totalScore += text.match(rule.regexp).length * rule.grade;
    }
    console.log([rule.regexp, matchResult && matchResult.length, rule.grade, matchResult && matchResult.length * rule.grade, totalScore]);
  });
  return totalScore;
})([{
  "regexp": /true/g,
  "grade": 1
}, {
  "regexp": /hate/g,
  "grade": -1
}, {
  "regexp": /dog/g,
  "grade": 0.8
}, {
  "regexp": /cat/g,
  "grade": -0.8
}], "Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend"));

i prefer using regular expressions instead of strings in this scenario, but you can always convert strings to regex at runtime as needed. Hopefully, this explanation helps.

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

The Process of Sending Values from app.js to a Vue File in Vue.js

My app.js is currently receiving a value called gtotal. I am trying to pass this value to the orderForm.vue file but am facing some difficulties in achieving this. require('./bootstrap'); window.Vue = require('vue'); window.EventBus ...

Guide: Utilizing JSON API data to generate marker labels on a leaflet map

Users are presented with points to click on. When a point is clicked, a menu displays text information. I have successfully placed the points, but when attempting to retrieve specific data from the database upon clicking a point, it does not show the marke ...

Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removi ...

Once this code is executed, Javascript ceases to function

I have developed a code snippet to create a typing effect similar to a command console. While the code is functioning well on its own, any additional code I add after it seems to malfunction. I've spent quite some time troubleshooting this issue witho ...

What causes jquery-ui resizable to set the width of the div with the "alsoResize" property?

I have created a series of divs structured like this: <div id="body_container"> <div id="top_body"> </div> <div id="bottom_body"> </div> </div> Additionally, I have implemented the following funct ...

Hiding a column in jQuery DataTables

Can the jquery datatables plugin be used to easily hide and show a table column? I've successfully refreshed the table data by using fnClearTable and fnAddData. However, I'm facing a challenge in one of my table views where I need to hide certa ...

Display relevant information in AngularJS according to the chosen category

I am looking to customize this accordion to display data based on the category selected from a dropdown. Currently, it shows all data and I would like to add a filter option. Below is my code snippet along with sample data from my database. Is there a wa ...

AngularJS Relationships with Hibernate

Working with two classes that have a one-to-one relation, I have successfully retrieved their data and displayed it in HTML using REST service and AngularJS. However, when attempting to display the airport ID on the asset page using {{asset.airport.id}}, n ...

The Math.random() function is responsible for producing a single random number

I have a unique idea for a keyboard that generates divs when keys are pressed. The keyboard functionality has already been implemented. Each div should be positioned randomly on the screen but still be grouped by letter. My approach involves adding a rando ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

Tips for developing a function that can identify the position of the largest integer within a given array

I need some help refining my function that is designed to identify the index of the largest number in an array. Unfortunately, my current implementation breaks when it encounters negative numbers within the array. Here's the code snippet I've bee ...

Retrieve essential file information from a Hadoop Distributed File System (HDFS) directory using Scala

While working with the org.apache.hadoop.fs package in Spark Scala, I encountered a problem. I am looking to extract specific file details (file name, block size, modification time) from a given directory. Here is the code snippet that I have tried: impo ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...

Animating a gradient within an SVG element following along an SVG path

I successfully created an SVG egg and animated a path while adding a gradient, but I am facing an issue. The linear gradient goes from top to bottom, but I want the dark color at 0% and the light color at 100%. Essentially, I want the gradient to follow th ...

Retrieve HTML content, including images, using Json in ASP .NET MVC4

Is there a way to send a Partial view result back to the view using Ajax and Json in ASP .NET MVC4? The HTML content also includes images. I've attempted to return data with the following code, but it's not functioning correctly. return PartialV ...

Tips for fixing an error encountered when running a react native project for the first time

I am encountering some errors while attempting to run this project for the first time and I am unable to resolve them. Below is the content of the package.json file: { "scripts": { "start": "expo start", "andro ...

Getting some clarity on how to structure a project using Node.js, Express.js, and React.js

I am in the process of developing a website for online shopping purposes, essentially an e-commerce platform. However, I am facing a dilemma where create-react-app sets up its own Node.js server to communicate with my backend (which handles MySQL queries) ...

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...

"Provide information, then open a new webpage by clicking on a button. Perform various actions with the form by using type

Is there a way to quickly submit form entries to my database and then automatically redirect to a new page? My current situation requires that submitted information is stored in the DB before directing users to a thank you page, all in one seamless click! ...

Using MVC to create dynamic JavaScript functions that call actions

Having trouble with dynamic JavaScript onchange event not firing in my application. Here's the code snippet from my action result: public ActionResult About() { ViewBag.Script = "<input type='text' name='myName&a ...