Codewars #1: Sort function



Codewars is really a nice place to practice coding. They have a variety of languages to practice on, you chose your pick, and start solving. I especially love the way they write the practice questions [wish my intro to programming course did the same] anywho [I get sidetracked a lot sorryNotsorry] I’ve been practicing on Javascript, one of the questions goes as:

Don’t get me wrong the problem is very easy. it’s a simple reverse sort function, with a little of typecasting and concatenation.  But there was something weird. Whenever I sort the array, I get this weird result:

 

 

As you can see in the console, I get 1 then 10. Yo javascript what up bro how are you sorting your variables? Luckily the Stackoverflow gods were there to help. Apparently, the way the sort function work is by sorting them in a lexicological order. The way to solve this problem is by using an anonymous function that looks something like this:

And now we have a fixed array to reverse the order we can just use b-a as the return statement, or use the reverse function. What I loved about this exercise is even though it’s a simple example, but made me learn about how the sort function works, and know the approach to solve the problem with sorts. if you want the detailed StackOverflow answer you can check it out here. And there’s this nice tutorial about the sort function here as well.

Happy coding

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *