Deadpool
Deadpool

Reputation: 8240

Sorting array of words by pure JavaScript

I am having a set of strings in array, and by pure javascript I am trying to sort them and print them out. I am only getting blank array. Can someone help me out?

<script> 
(function(){
    var a = ["AB", "SU", "MN", "AC", "QA", "DZ", "CM", "EP"];
    var b = [];
    for(i=0;i<a.length;i++){
        var temp = a[i].split('')[0];
        for(j=0;j<b.length;j++){
            if (temp < b[j].split('')[0]){
                b[j] = push(a[i]);
            }
        }
    }
    console.log(b);
})();
</script> 

Also I need to take in account comparision of second, third, fourth characters if they exist, but I am doomed even in fist letter comparison in string. Pls, take that also in account.

Upvotes: 2

Views: 625

Answers (2)

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

Here you go. EDIT Consider comments i was wrong a little bit. Now all fine.

var a = ["AB", "SU", "MN", "AC", "QA", "DZ", "CM", "EP"];
var b = a.sort();
//also can use reverse here.
console.log(b);

And here is jsbin

https://jsbin.com/xikamitole/1/edit?html,js,console

Hope this helps.

Upvotes: 3

Rachid
Rachid

Reputation: 76

All you need is just calling

a.sort()

PS: sort is going to update your array (not just returning a copy of your array sorted)

Upvotes: 4

Related Questions