1

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!

7
  • 1
    Should searchkey not be a string as well? Commented Nov 7, 2014 at 7:37
  • yes, search key would always be a string like apple, banana etc. Its just an example what I explained. Commented Nov 7, 2014 at 7:38
  • 1
    I don't get the logic of sorting. What if searchKey is 238? Or 111? Or 321? Commented Nov 7, 2014 at 7:39
  • So you want the result array contains matched strings first, then the rest of original array sorted by alphanum. order. Isn't it? Commented Nov 7, 2014 at 7:45
  • yes, You are right. Most accurate will go at the top, 2nd most accurate will go after and so on... Commented Nov 7, 2014 at 7:55

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Fantastic, thats all what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.