Array sort by string matching

by trolleymusic

HTML

<input type="text" id="match">
<hr>
<output id="matches">

CSS

input, output {
    display: block;
    margin: 20px;
}

output {
    min-height: 200px;
    border: 1px dotted #333;
    padding: 10px;
}

JavaScript

var suggestions = [
    "Making the most of my money",
    "Taking a business global",
    "Growing a business",
    "Spending more time with my family",
    "Planning for retirement",
    "Saving time managing money",
    "Taking a company public",
    "Confidence banking internationally",
    "Retirement funds",
    "Global business money",
    "Managing retirement business",
    "Public global company money",
    "Confidence in retirement pensions",
    "Global finance solutions",
    "Making most of my retirement",
    "Global money management",
    "Buying a first home",
    "Saving for a house deposit",
    "Buying a holiday home",
    "Buying a second property",
    "Buying property in the UK",
    "Buying property overseas",
    "Expanding a property portfolio",
    "Starting a property portfolio",
    "Set up a retirement fund",
    "Plan for retirement",
    "Living comfortably with a retirement fund",
    "Planning for private healthcare",
    "Understand tax implications",
    "Plan for a wedding",
    "Paying childrens education fees",
    "Setting up a trust fund for grandchildren",
    "Supporting elderly relatives",
    "Travel the world",
    "Funding a vintage wine collection",
    "Protecting income",
    "Planning a luxury holiday",
    "Starting your own business",
    "Giving to charity",
    "Managing money overseas"
]
    
    var SortMatch = function(s, term, alphaFallback) {
    
    // sort into alphabetical order as a fallback
    if (alphaFallback) { s = s.sort(); }
    
        
    // we should increase the complexity of this - maybe allow a regexp or array as well as just a string
    var r = new RegExp(term,'gi')
    return s.sort(function(a,b) {
        //compare a and b and return -1, 0, or 1
        var am = a.match(r);
        var bm = b.match(r);
am = am ? am.length : 0;
bm = bm ? bm.length : 0;

console.log(am);        

        if (am > bm) {
            return -1;            
        } else if (am == bm) {
           ...