Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort alphabetically matching the beginning of string then alphabetically for contained text

I need help sorting through some data. Say I type "piz" in a searchfield. I get in return and array with all the entries that contain "piz".

I now want to display them in the following order:

pizza 
pizzeria
apizzetto
berpizzo

First the items that start with what I typed in alphabetical order then the ones that contain what I typed in alphabetical order.

Instead if I sort them alphabetically I get the following

apizzetto
berpizzo
pizza 
pizzeria

Does anyone know how to do this? Thanks for your help.

like image 414
Leonardo Amigoni Avatar asked May 13 '12 15:05

Leonardo Amigoni


2 Answers

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/

like image 140
jfriend00 Avatar answered Nov 15 '22 15:11

jfriend00


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;
     });
 };
like image 27
justtal Avatar answered Nov 15 '22 15:11

justtal