You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JS/JQuery中实现基于标签匹配度的最优问答匹配

Solution for Multi-Tag Matching & Sorting in Q&A Array

Let's tackle this problem—your current code only grabs the last item with a matching tag, but we need to find the one with the most matching tags instead. Here's how to do it properly with jQuery/JS:

Step-by-Step Approach

  1. Process User Input: Split the input into individual keywords, normalize to lowercase (to make matching case-insensitive), and filter out empty strings.
  2. Calculate Match Scores: For each item in your objectArr, count how many of its tags overlap with the user's keywords.
  3. Find Top Match: Sort the array by match score (highest first) and pick the top result, or handle ties if needed.
  4. Display the Answer: Inject the best-matching answer into your #answer div.

Full Working Code

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="user_input" placeholder="Enter your issue keywords...">
<button id="submit">Send</button>
<div id="answer"></div>

<script>
var objectArr = [{ 
    "tags": ["windows", "3cx", "webclient", "hoe", "venster", "windows-venster"], 
    "answer": "Maak op je bureaublad een sneltoets aan en kies als doel:&lt;br/&gt;“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” –app=https://pbx000000.fluxcloud.eu:5001/webclient &lt;br/&gt;Hier verander je de 000000 in de link naar het juiste PBX-nummer wat er hoort." 
}, { 
    "tags": ["swyx", "toestel", "opstarten", "blijft", "opnieuw", "mijn", "werkt niet"], 
    "answer": "Tijdens een software-update is de stroom mogelijk van het toestel af geweest. &lt;br/&gt; Je kan het toestel opsturen naar ons om de software te herstellen.&lt;br/&gt; De kosten van het herstellen van het toestel bedraagt €25,-" 
}, { 
    "tags": ["toestel", "vast", "bellen", "kan niet", "werkt niet"], 
    "answer": "Zorg ervoor dat de telefonie-applicatie (SwyxIt!) is opgestart en dat jouw toestel is ingelogd op je eigen naam.&lt;br/&gt; Als dat het geval is, ga dan in SwyxIt! naar: Instellingen – CTI – CTI gebruiken – start koppelen." 
}, { 
    "tags": ["client", "swyx", "inloggen", "kan niet", "werkt niet"], 
    "answer": "Controleer de tijd op de pc, deze mag niet meer dan 3 minuten afwijken van de tijd op de Swyxserver.&lt;br/&gt; Klopt de tijd op je pc, maar kun je nog steeds niet inloggen?&lt;br/&gt; Controleer dan je SwyxIt!-versie. Deze mag niet nieuwer zijn dan de OZMO cloud-omgeving." 
}, { 
    "tags": ["beltoon", "geen", "swyx", "swyxphone", "mijn"], 
    "answer": "SwyxPhone L640 laat in het display een belsymbool zien waar een streep doorheen staat.&lt;br/&gt; De beltonen van het toestel zijn op dat moment uitgeschakeld.&lt;br/&gt; Door de &lt;b&gt;“*”&lt;/b&gt; toets voor langere tijd in te drukken, kun je de beltonen weer activeren." 
}];

$("#submit").click(function(e) {
    e.preventDefault(); // Prevent accidental form submission if this is in a form
    var input = $("#user_input").val().trim().toLowerCase();
    if (!input) {
        $("#answer").html("Please enter some keywords to search.");
        return;
    }
    
    // Split input into keywords (handles multiple spaces)
    var userKeywords = input.split(/\s+/);
    
    // Calculate match score for each item
    var scoredItems = objectArr.map(item => {
        var matchCount = 0;
        // Check each user keyword against the item's tags
        userKeywords.forEach(keyword => {
            if (item.tags.some(tag => tag.toLowerCase() === keyword)) {
                matchCount++;
            }
        });
        return { ...item, score: matchCount };
    });
    
    // Sort items by score (highest first), keep original order for ties
    scoredItems.sort((a, b) => b.score - a.score);
    
    // Get the top matching item
    var topMatch = scoredItems[0];
    
    if (topMatch.score === 0) {
        $("#answer").html("No matching answers found.");
    } else {
        $("#answer").html(topMatch.answer);
        // Optional: Uncomment to show match count for debugging
        // $("#answer").append(`<br><small>Matched ${topMatch.score} tags</small>`);
    }
});
</script>

Key Improvements Over Your Original Code

  • Case Insensitivity: Converts both input and tags to lowercase so matches aren't missed due to capitalization (e.g., "Swyx" vs "swyx").
  • Match Scoring: Instead of overwriting the answer on every match, we count how many tags match for each item.
  • Sorting: We sort the array by match score to ensure the most relevant answer comes first.
  • Edge Cases: Handles empty input and cases where no tags match at all.

Handling Ties (Optional)

If multiple items have the same highest match score and you want to show all of them, replace the final display block with:

if (topMatch.score === 0) {
    $("#answer").html("No matching answers found.");
} else {
    var topMatches = scoredItems.filter(item => item.score === topMatch.score);
    var answersHtml = topMatches.map(item => `<div class="answer-item">${item.answer}</div>`).join("");
    $("#answer").html(answersHtml);
}

内容的提问来源于stack exchange,提问作者Webdeveloper_Jelle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:08:25