javascript - Complex array ordering -
suppose have following array:
var articles = [ { id: 7989546, tags: [ "98#6", "107#6", "558234#7" ] }, //... ]
each element of array represents (partially) kind of content in our website. has id , tagged people (#6) and/or topics (#7).
the user going provided cookie containing suggested or recommended tags, this:
var suggestions = [ "46#6", "107#6", "48793#7" ]
consider these tags suggestions shown end user, "maybe interesed in reading..."
the suggestions
array ordered tag prioritiy. means, first tag more relevant user second tag.
now, want order articles
array in same way, is, tag priority.
no filters should applied articles
array guaranteed have elements have @ least 1 tag suggestions
array.
if have article tags: [ "98#6", "107#6", 558234#7" ]
, 1 tags: [ "46#6", "36987#7" ]
, want latter first, because tag 46#6
has more priority 107#6
in suggestions
array.
how can achieve kind of ordering (using 2 arrays)?
note: jquery solutions gladly accepted.
just make own sort function , use .indexof
in order check tag existence. issue going have decide handle on own makes sense collisions. if article tagged priority 1 tag, article tagged 3 lower priority tags, gets precedence? there logic involved there , in suggested solution take total of priority using length of suggestions , summing priorities. can adapted give different type of collision detection if wish, approach same.
step 1: create compare function
this going order array descending base on result tagcount. if tagcount returns value of 6 right, , value of 3 left, 6 ordered first.
var comparefn = function(left,right){ return tagcount(right.tags) - tagcount(left.tags); };
step 2: create tagcount "algorithm" determining priority
this gives precedence earliest occurring match, give weight multiple later occurring matches. taking matched index subtracted length of match array (suggestions). if there 5 suggestions, , first suggestion matched, going end being value of 5 (length=5 - index=0).
var tagcount = function(tags){ var count = 0; for(var = 0; < tags.length; i++){ var weight = suggestions.indexof(tags[i]); if(weight > -1) count += tags.length - weight; } return count; }
stack snippet
var articles = [ { id: 7989546, tags: [ "107#6", "558234#7" ] }, { id: 756, tags: [ "98#6", "558234#7" ] }, { id: 79876, tags: [ "98#6", "107#6", "558234#7" ] }, { id: 7984576, tags: [ "98#6", "107#6", "46#6" ] } ]; var suggestions = [ "46#6", "107#6", "48793#7" ]; var comparefn = function(left,right){ return tagcount(right.tags) - tagcount(left.tags); }; var tagcount = function(tags){ var count = 0; for(var = 0; < tags.length; i++){ var weight = suggestions.indexof(tags[i]); if(weight > -1) count += tags.length - weight; } return count; } var = articles.sort(comparefn); console.log(a); document.queryselector("#d").innerhtml = json.stringify(a);
<div id="d"></div>
Comments
Post a Comment