3

I would like to know how can I sort strings in javascript containing comma separated values in different order e.g.

    var str1 ="aaa,SC,AAA,mc,mc,aaa";
    var str2 ="AAA,SC,aaa,aaa,mc,mc";

So basically i want to sort them and do an equality comparion check.

    if(str1==str2)
    // do something...

Your help will be appreciated.

Thanks

2 Answers 2

18
str.split(",").sort().join(",")
Sign up to request clarification or add additional context in comments.

2 Comments

That use case works, what if Str1="aaa,SC,140,mc,22,aaa"; str2 ="140,SC,aaa,aaa,mc,22"; mean numbers as string will that work as. Also what if each of them is empty?
I don't see any reason why it wouldn't work with numbers or empty strings. You should try it.
0
function areSame(csv1, csv2) {
    return csv1.split(",").sort().join() === csv2.split(",").sort().join();
}

var str1 = "aaa,SC,AAA,mc,mc,aaa";
var str2 = "AAA,SC,aaa,aaa,mc,mc";

alert("areSame = " + areSame(str1, str2));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.