问题描述
我需要一些整理数据的帮助.假设我在搜索栏中输入"piz".我得到返回并包含所有包含"piz"的条目的数组.
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.
推荐答案
您可以将数据拆分为两个数组,一个数组以您的输入开头,另一个数组不以您的输入开头.分别对它们进行排序,然后合并两个结果:
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);
您可以在这里看到它的工作: http://jsfiddle.net/jfriend00/nH2Ff/
You can see it work here: http://jsfiddle.net/jfriend00/nH2Ff/
这篇关于Javascript排序按字母顺序匹配字符串的开头,然后按字母顺序匹配包含的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!