Sai
Sai

Reputation: 25

How to sort an array of Strings in Jquery with any specific sort order given

I have and array of strings:

var arrStr = ["Ron", "Jhon", "Mary", "Alex", "Ben"];

The above array is the default sort order that I require. I have another array of Strings:

var arrStr2 = ["Mary", "Alex", "Jhon"];

I wanted to sort arrStr2 with the sort order in arrStr. (the order in arrStr also can be changed, accordingly the arrStr2 should be sorted). arrStr2 can have more values also, but the values will be only from any of the values in array arrStr

After sorting I need an out put for arrStr2 as ["Jhon","Mary","Alex"];

How can I achieve this using jQuery?

Upvotes: 0

Views: 104

Answers (3)

gurvinder372
gurvinder372

Reputation: 68393

After sorting I need an out put for arrStr2 as ["Jhon","Mary","Alex"];

simply try this

arrStr2.sort(function(a,b){ return arrStr.indexOf(a) - arrStr.indexOf(b) });

Now arrStr2 will have the value you are expecting,

DEMO

var arrStr = ["Ron", "Jhon", "Mary", "Alex", "Ben"];

var arrStr2 = ["Mary", "Alex", "Jhon"];

arrStr2.sort(function(a,b){ return arrStr.indexOf(a) - arrStr.indexOf(b) });

document.body.innerHTML = JSON.stringify( arrStr2, 0, 4 );

Upvotes: 1

Dhananjaya Kuppu
Dhananjaya Kuppu

Reputation: 1322

This is one more approach:

var rank = {};
arrStr.forEach(function(e, i){rank[e] = i;});
arrStr2.sort(function(a, b) {return rank[a] - rank[b];});

Upvotes: 0

georg
georg

Reputation: 214959

Just compute the intersection, no need to sort():

var arrStr = ["Ron", "Jhon", "Mary", "Alex", "Ben"];
var arrStr2 = ["Mary", "Alex", "Jhon"];

result = arrStr.filter(x => arrStr2.includes(x))

document.write('<pre>'+JSON.stringify(result,0,3));

(ES5 backporting left as an exercise).

Upvotes: 1

Related Questions