2

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.

8
  • 2
    Use the Array.prototype.sort method. Commented Aug 27, 2016 at 13:07
  • care a fiddle sir? Commented Aug 27, 2016 at 13:08
  • I don't know why you're splitting up the strings. You can compare string with just a[i] < b[j]. Commented Aug 27, 2016 at 13:08
  • Don't use fiddle, use Stack Snippet Commented Aug 27, 2016 at 13:09
  • 1
    Yes, it will compare the whole strings with each other. This is very basic Javascript. Commented Aug 27, 2016 at 13:13

2 Answers 2

4

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)

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

1 Comment

without sort function
3

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.

8 Comments

The callback here is incorrect. The callback passed to .sort() should return a negative number if the first parameter should sort before the second, 0 if they have the same sort order, and 1 if the second should sort before the first.
The comparison function is supposed to return a number, v > k returns a boolean.
Well in here we have strings. So consider example all valid.
Sometimes bad code works despite being incorrect. That doesn't make it correct.
Ty guys for fixing my issue. And glad that @Peterson got his answer.
|

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.