0

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?

1
  • do you have a case where arrStr2 may have duplicates? Commented Mar 24, 2016 at 11:58

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Assuming that it is left as an exercise for everyone (not only OP) :) ES5 would be arrStr2 = arrStr.filter(function(value) { return arrStr2.indexOf(value) > -1; })
1

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

1 Comment

Thanks !. It does the sorting, but the result is a JSON and that is which is converted to String. Now the new array which I get are having all values with extra spaces appended, which I do not need.
0

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

Comments

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.