Absolute Beginer Absolute Beginer - 4 months ago 10
JSON Question

Multiple words search and calculation algorithm (Angular/Javascript)

I'm loading json file from database with two fields words and grade. Each word is graded for example true has 1 while lie has -1. Then i take input from text filed and i need to grade it based on grades from JSON file and then calculate score by summarizing the grades, but i just can't seem to find the way to do that. Words that are not in file are not being calculated.

I tried string.search match but it's to complicated and in the end i couldn't get result the way i wanted. I tried array searches same thing. I searched for on line solution, but no one has done anything similar so i can't copy it.

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

The first thing I'd do is turn your JSON data into a map which can easily be searched - key would be the word, and value the grade:

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);

Then, its just a case of splitting your string, whilst also calculating the total score - again reduce can be used

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);

Note that I have manually removed punctuation in the above input - I'll leave that as an exercise for you.

Also note that "cats" != "cat" so some of your words wont be found!