thisuser
thisuser

Reputation: 129

Is it possible to filter and arrange a list by keyword relevance in javascript?

Say I have a list of items with multiple classes (keywords) like

<ul>
<li class="domestic tail feline">Cat</li>
<li class="wild tail canine">Wolf</li>
<li class="domestic tail canine">Dog</li>
<li class="wings beak domestic">Parrot</li>
<li class="wild tail feline">Lion</li>
</ul>

And then on the previous page a user selects 3 features from a select box and clicks next. Saving the keywords using localstorage, how can you, with javascript or jQuery, then display the list in order of most matching keywords?

So if I had input domestic, feline and wings the first item in the list would be Cat followed by Parrot, then Dog, Lion, and Wolf.

Upvotes: 0

Views: 691

Answers (2)

Bergi
Bergi

Reputation: 665364

var $ul = ..., // the list element
    keywords = ["domestic", "feline", "wings"]; // get that list from an input,
                                                // localstorage or whereever
$ul.children().sort(function(a, b) {
    var score = 0,
        $a = $(a),
        $b = $(b);
    for (var i=0; i<keywords.length; i++)
        score += $a.hasClass(keywords[i]) - $b.hasClass(keywords[i]);
        // if only a has the keyword, it adds 1, if only b has it 1 is substracted,
        // and if they both have if or not the score does not change.
    return score;
}).appendTo($ul); // re-append in the right order

This is a simple example of sorting a jQuery selection, you could make it more performant if you assigned each element a score of matching keywords and compared those numbers only.

Upvotes: 0

Josh
Josh

Reputation: 276

Not using jQuery, you would have to put those words and their keywords into an array.

Then loop through them comparing them to the 3 selected words to give them a value/score.

Then you would have to order these words based on the their scores. Here is a link about sorting a javascript array : How to sort an associative array by its values in Javascript?

Using that ordered array you can loop through it to create the list-items and dynamically write them into a div using the "innerHTML" property.

I would setup an array like so(there are several ways you could go about this):

var listItems = new Array();
function listItem(displayWord){
    this.word = displayWord;
    this.keywords = new Array();
    this.matches = 0;
}

listItems['cat'] = new listItem('cat');
listItems['cat'].keywords.push('domestic');
listItems['cat'].keywords.push('tail');
listItems['cat'].keywords.push('feline');

for (x in listItems) {
    for (var c = 1; c < listItems[x].keywords.length; c++) {

    }
}

Upvotes: 1

Related Questions