Organize and Group Matching Strings in an Array using Node.js

I'm currently developing an FAQ system that includes a large number of question-answer pairs. My goal is to group similar questions together and I've been utilizing the npm set-clustering package for this purpose.

While the package offers a good match based on token matching, it requires me to specify the number of groups to create.

My ideal scenario would be for the grouping to be automatic, with the algorithm determining the appropriate number of groups to be created (Unsupervised learning).

If you know of any other package or platform that could assist me, please let me know.

Sample Questions:

What is the pricing of your product?

Can I speak to your representative?

Hi

Hi Friend

Hi, Good Morning

How much does it cost?

Current Result: (When specifying '3' as the number of groups)

(Hi, Hi Friend)

(What is the pricing of your product?, How much does the product cost?)

(Can I speak to your representative?, Hi, Good Morning)

Desired Grouping: (Without providing '3' as input)

(Hi, Hi Friend, Hi, Good Morning)

(What is the pricing of your product?, How much does the product cost?)

(Can I speak to your representative?)

Current Code:

var cluster = require('set-clustering');

for (let row of resp) {
    articles.push({
        title: row.que,
        tags: row.tags
    });
}

function similarity(x, y) {
    var score = 0;
    x.tags.forEach(function(tx) {
        y.tags.forEach(function(ty) {
            if (tx == ty)
                score += 1;
        });
    });
    return score;
}

// I want the grouping to be done autonomously without specifying the number of groups
var groups = c.evenGroups(3);

var titles = groups.map(function(group) {
    return group.map(function(article) {
        return article.title;
    });
});

console.log(titles);

Refer https://www.npmjs.com/package/set-clustering

Answer №1

const ss = require('sentence-similarity')
const thesaurus = require("thesaurus");

const sentenceSim = ss.sentenceSimilarity;
const simScore = ss.similarityScore;
const minFunc = (a,b) => {
    if (a < b) return a;
    else return b;
}

const checkSimilarity = (sentence1, sentence2) => {
    const s1 = sentence1.split(' ');
    const s2 = sentence2.split(' ');
    const numbers = [];
    for (const e of s1) {
    const syn = thesaurus.find(e);
    for (let i=0; i<syn, i<5; i++) {
        e = syn[i];
        numbers.push(sentenceSim(s1, s2, winkOpts)['score'] / minFunc(s1.length, s2.length));
    } 
    }
    return Math.max.apply(null, numbers) >= 0.375;
}

const winkOpts = { f: simScore.winklerMetaphone, options : {threshold: 0} }
const filterWords = (source, maximum = 5) => {
  let _source, matches, x, y;
  _source = source.slice();
  matches = [];
  for (x = _source.length - 1; x >= 0; x--) {
    let output = _source.splice(x, 1);
    for (y = _source.length - 1; y >= 0; y--) {
      if (checkSimilarity(output[0], _source[y])) {
    output.push(_source[y]);
    _source.splice(y, 1);
    x--;
      }
    }
    matches.push(output);
  }
  return matches;
}
const inputWords = ['Your', 'word', 'list'] 
const result = filterWords(inputWords);

Utilizing the Thesaurus library for identifying analogous terms. https://www.npmjs.com/package/thesaurus

Employing Sentence Similarity to enhance matching capabilities. https://www.npmjs.com/package/sentence-similarity

Delivering satisfactory outcomes with the provided dataset.

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

Implementing a function trigger upon selection in JavaScript

I'm currently studying JavaScript and working on a basic project that involves generating random strings of different lengths. If you're interested, feel free to check out my codepen code [here][1]. My question revolves around the functionality ...

Submitting an HTML form with no input data

Looking to dynamically pass arguments between pages using the code below: <script type="text/javascript> function buildAndSubmitForm(index){ <? $args = 't='.$team.'&s='.$season.'&l='.$league.&apo ...

Issue with file upload: The view is not refreshing in response to non-angular events

I am having an issue with my upload component where the view is not updating when the onchange event fires. Even though I can see the file names being logged, nothing is happening on the screen. My approach involves using a directive so that I can easily ...

Utilizing an array in a PHP URL and incorporating it into JavaScript operations

In this PHP file, I am working on validating only numeric input for text-boxes with the ids "Mobile" and "Home": $elementids = array("Mobile","Home"); $serialized = rawurlencode(serialize($elementids)); $testvar='validate-nums.php?elementids='. ...

Issue: Dynamic server is experiencing abnormal increase in usage due to headers on Next version 13.4

Encountering an error in the following function. It's a basic function designed to retrieve the token from the session. 4 | 5 | export async function getUserToken() { > 6 | const session = await getServerSession(authOptions) | ...

How to delete the final character from a file stream using node.js and the fs module

My current project involves using node.js to create an array of objects and save them to a file, utilizing the fs library. Initially, I set up the write stream with var file = fs.createWriteStream('arrayOfObjects.json'); and wrote an opening brac ...

selenium tutorial: Testing tooltip functionality with Python

<div class="icon_png information icon_baggageyes" title="getTooltip()"></div> Here, a tooltip is displayed using the getTooltip() function. Is there a method to retrieve the return value of the function for testing with Selenium? ...

"Enhance Your Website with Drag-and-Drop Cart Functionality using HTML

Seeking assistance from anyone who has the knowledge. I've searched through similar questions on this platform but haven't been able to resolve my issue. Currently, I'm working on developing a basic shopping cart using HTML5 (Drag and Drop ...

Trouble with npm installation on Windows following node update

After updating my Node.JS last night, my npm install function stopped working. I tried uninstalling and reinstalling Node, but it didn't solve the issue. My system is running on Windows 8.1 with Node version 8.9.4 and NPM version 3.3.12. The error mes ...

Use the Arrow Keys to guide your way through the Page

I am looking to enhance user experience by allowing them to easily navigate through my webpage using the arrow keys on their keyboard. The goal is for users to be able to move from one section to the next in a seamless manner, unless they are focused on an ...

Angular 2 encountering an error with the HTTP GET request

I am currently facing some challenges with subscribing to the response while using the http method get request. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http&ap ...

Module not defined error

Here is the code for my HTML page: <!DOCTYPE html> <!-- define angular app --> <html ng-app="daily"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" c ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

Issue: Unable to locate element with the specified selector: #email

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://discord.com/register'); await page.screenshot({path: 'b.png ...

Exploring Node.js Express: Understanding the Difference Between Modules and Middleware

I am working on an express rest api and need to create a PDF document with a link to download it. I have successfully generated the PDF, but now I want to create a route specifically for returning the PDF link. In addition, I also need other routes that ...

Other options besides re-flowing and repainting

After doing some research on various platforms like Stack Overflow, I've come across information stating that re-paints and re-flows can be quite taxing on a browser's resources. I am interested in learning about alternative CSS/JS techniques to ...

Determining the angular difference between the direction of particle motion and a straight line

Currently, I am in the process of developing a simulation involving a bouncing ball. In this simulation, users have the ability to place lines on the canvas that the ball can collide with by dragging from one point to another. There are specifically four t ...

After a period of time, NodeJS abruptly crashes while processing a CSV file

Recently, I've been working on a project that involves converting CSV data into XML. To accomplish this, I have been using the fs.createReadStream() method to read the CSV file. However, I encountered an issue where the terminal crashes unexpectedly a ...

The PHP script is not being activated by AJAX

I am completely baffled by the situation at hand. Sometimes, I open a different browser to test my changes and it works as expected. But then, when I try again, it fails. It's driving me crazy. On syllableapp.com, I set up a MySQL database that I can ...

Utilizing jQuery/Javascript to replicate the data from a table while excluding the header and then pasting it to the

I am attempting to replicate the data from a table while disregarding the header/title row and copying it to the clipboard in the exact same way as manual selection and copy. I came across a post on how to choose Select a complete table with Javascript (t ...