简体   繁体   中英

Javascript Sort array matches based on closest match

I'm implementing a search that gives suggestions based on the query. It checks if any of the suggestions includes the query. However, the suggestions aren't sorted by the closest match. How do I sort them?

This is my code:

this.suggestions = this.allSuggestions.filter(s => s.Subject.includes(this.query) || s.Child_Subject.includes(this.query))

I just made a sweetScore and SweetSort today. It hurt my minuscule brain. Hopefully it works for you like it does for me.

 //<![CDATA[ var doc, M, I, special, unspecial, regEsc, sweetScore, SweetSort; // for use on other loads addEventListener('load', function(){ // make sure DOM is loaded doc = document; M = function(tag){ return doc.createElement(tag); } I = function(id){ return doc.getElementById(id); } special = function(str){ // for use with .innerHTML not .value or .text return str.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } unspecial = function(str){ return str.replace(/&amp;/g, '&').replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>'); } regEsc = function(string){ return string.replace(/[.*+?^()[\\]|{}\\\\$]/g, '\\\\$1'); } sweetScore = function(string){ for(var i=0,str=string.toLowerCase(),s=0,n=1,l=str.length; i<l; i++,n++){ s += Math.pow(str.charCodeAt(i), n); } return s; } SweetSort = function(array){ var stash; this.candy = function(array){ stash = array.slice(); return this; } if(array !== undefined)this.candy(array); this.sweet = function(string){ var str = regEsc(string), score = sweetScore(str), rx = new RegExp('^'+str, 'i'), p = [], r; if(str !== ''){ for(var i=0,l=stash.length; i<l; i++){ if(stash[i].match(rx)){ p.push(stash.splice(i, 1)[0]); i--; l--; } } p.sort(function(a, b){ return a.length-b.length; }); } stash.sort(function(a, b){ return Math.abs(score-sweetScore(a))-Math.abs(score-sweetScore(b)); }); r = p.concat(stash); stash = stash.concat(p); return r; } } var sweet_score_in = I('sweet_score_in'), sweet_sort = I('sweet_score'), sweet_sort_in = I('sweet_sort_in'), sweet_sort = I('sweet_sort'); sweet_score_in.onkeyup = function(){ sweet_score.innerHTML = sweetScore(this.value); } var sm = new SweetSort(['how', 'now', 'brownest', 'Brown', 'Cow']); sweet_sort_in.onkeyup = function(){ sweet_sort.innerHTML = special(JSON.stringify(sm.sweet(this.value.trim()))); } sweet_sort.innerHTML = special(JSON.stringify(sm.sweet(''))); I('content').style.display = 'block'; // in case you are creating other DOM parts with JavaScript });// end load //]]> 
 /* external.css */ *{ padding:0; margin:0; box-sizing:border-box; overflow:hidden; } html,body{ width:100%; height:100%; background:#aaa; color:#000; } body{ position:relative; font:22px Tahoma, Geneva, sans-serif; } body>*{ position:absolute; } #content{ display:none; width:100%; height:100%; } .page{ position:relative; width:100%; height:100%; float:left; } .bar{ width:100%; height:38px; padding:3px; background:#ccc; color:#000; } h1{ font-size:28px; margin-left:3px; } .main{ height:calc(100% - 38px); padding:5px; overflow-y:auto; } label{ display:block; height:26px; font-weight:bold; } label>em{ font-size:14px; } input[type=text]{ width:100%; font:22px Tahoma, Geneva; padding:0 5px; border:1px solid #aaa; border-radius:5px; } input[type=text]+div{ height:28px; margin-bottom:5px; } 
 <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8' /> <meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' /> <title>sweetScore &amp; SweetSort - by Jason Raymond Buckley</title> <link type='text/css' rel='stylesheet' href='external.css' /> <script type='text/javascript' src='external.js'></script> </head> <body> <div id='content'> <div class='page'> <div class='bar'><h1>sweetScore &amp; SweetSort</h1></div> <div class='main'> <label for='sweet_score_in'>sweetScore</label> <input id='sweet_score_in' type='text' value='' /> <div id='sweet_score'>0</div> <label for='sweet_match_in'>SweetSort <em>['how', 'now', 'brownest', 'Brown', 'Cow']</em></label> <input id='sweet_sort_in' type='text' value='' /> <div id='sweet_sort'></div> </div> </div> </div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM