Javascript sort alphabetically matching the beginning of string then alphabetically for contained text
You can split the data into two arrays, one that starts with your input and one that doesn't. Sort each separately, then combine the two results:
var data = [
'pizzeria',
'berpizzo',
'apizzetto',
'pizza'
];
function sortInputFirst(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 = sortInputFirst('piz', data);
You can see it work here: http://jsfiddle.net/jfriend00/nH2Ff/
The right full solution is:
var data = [
'pizzeria',
'berpizzo',
'apizzetto',
'pizza'
];
var _sortByTerm = function (data, term) {
return data.sort(function (a, b) {
return a.indexOf(term) < b.indexOf(term) ? -1 : 1;
});
};
var result = _sortByTerm(data, 'piz');
If you want object sort, use this function:
var _sortByTerm = function (data, key, term) {
return data.sort(function (a, b) {
return a[key].indexOf(term) < b[key].indexOf(term) ? -1 : 1;
});
};
Here's another one:
var str = 'piz';
var arr = ['apizzetto','pizzeria','berpizzo','pizza'];
arr.sort(function(a,b) {
var bgnA = a.substr(0,str.length).toLowerCase();
var bgnB = b.substr(0,str.length).toLowerCase();
if (bgnA == str.toLowerCase()) {
if (bgnB != str.toLowerCase()) return -1;
} else if (bgnB == str.toLowerCase()) return 1;
return a < b ? -1 : (a > b ? 1 : 0);
});
console.log(arr);