使用纯JavaScript在搜索文本匹配的基础上进行数组排序 [英] Array sort on the basis of search text matching using pure javascript

查看:50
本文介绍了使用纯JavaScript在搜索文本匹配的基础上进行数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一种基于搜索字符串对数组进行排序的合适方法.例如,这是一个数组

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"];

我想要的是

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]);
    } 
}

正在等待宝贵的建议!

推荐答案

    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));

这篇关于使用纯JavaScript在搜索文本匹配的基础上进行数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆