Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

sorting - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...