I am working on some suitable way of sorting an array on the basis of search string. For example here is an array
var myarray = ["2386", "1234", "3867"];
and here is the string which I want to search in the above array
var searchkey = 123;
Upon sorting on the basis of search string, the result should be like this
var filtered_array= ["1234", "2386", "3867"];
What I want is
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]);
}
}
Waiting for valuable suggestions!
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));
I have used levinstien for the string comparison, you can check the fiddle demo.
levenstien source = https://github.com/gf3/Levenshtein ,
my code is
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);
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.