Javascript to sort the beginning match string in input reserved word list

Add wordlist in searchWord.js

window.getSearchWords = function() {
    return [
	'angular',
	'angularjs',
  	'ionic',
	'javascript',
	'node',
	'php',
	'pull',
	'push',
	'note'
    ];
}

Add following code in search, we can split the data into two arrays, one that starts with input and one. Sort each separately, then combine the two results:

function sortInputMatch(input, data) {
       var first = [];
       var others = [];
       for (var i = 0; i < data.length; i++) {
           if (data[i].indexOf(input) == 0) {
               first.push(data[i]);
           } else {
               others.push(data[i]);
           }
       }
       first.sort();
       others.sort();
       return (first.concat(others));
   }

   var results = sortInputMatch(query, matches);

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top