我正在研究一种基于搜索字符串对数组进行排序的合适方法。例如,这是一个数组
var myarray = ["2386", "1234", "3867"];
这是我要在上面的数组中搜索的字符串
var searchkey = 123;
根据搜索字符串排序后,结果应该是这样的
var filtered_array= ["1234", "2386", "3867"];
我想要的是
for(var i = 0; i < myarray.length; i++) {
if (myarray[i].indexOf(searchkey) > 1)
{
filtered_array.push(myarray[i]);
}else{
unfiltered_array.push(myarray[i]);
}
}
等待有价值的建议!
答案 0 :(得分:2)
var myarray = ["2386", "1234", "3867"], searchkey = '123';
function mySort(arrKeys,searchkey){
var matchedKeys = [], notMatchedKeys = [];
for(var i = 0; i < arrKeys.length; i++) {
if (arrKeys[i].match(searchkey) ) {//dummy logic
matchedKeys.push(arrKeys[i]);//push on the basis of order
}else{
notMatchedKeys.push(arrKeys[i]);
}
}
return matchedKeys.concat(notMatchedKeys);
}
console.log( mySort(myarray,searchkey));
答案 1 :(得分:1)
我使用levinstien进行字符串比较,您可以查看fiddle demo.
levenstien source = https://github.com/gf3/Levenshtein,
我的代码是
function compare(a, b) {
var leva = new Levenshtein(a,searchkey).distance;
var levb = new Levenshtein(b,searchkey).distance;
return leva-levb;
}
var myarray = ["2386", "1234", "3867"];
var searchkey = "123";
myarray.sort(compare);
答案 2 :(得分:0)
var myarray = ["1234", "3432","2324","1230","3842","1236"];
var searchkey = 123;
var filtered_array= [];
for(var i = 0; i < myarray.length; i++) {
if (myarray[i].contains(searchkey)) {
filtered_array.push(myarray[i]);
delete myarray[i];
}
}
var result_arr = filtered_array.concat(myarray);
for(var j=0;j<result_arr.length;j++){
if (result_arr[j] === undefined){
result_arr.splice(j,1);
}
}
console.log(result_arr)