In JavaScript, we can sort the elements of an array easily with a built-in method called the sort( ) function.
However, data types (string, number, and so on) can differ from one array to another. This means that using the sort( ) method alone is not always an appropriate solution.
In this post, you will learn how to sort an array in JavaScript by using the sort( ) method for strings and numbers.
Array of Strings
Let's start with strings:
const teams = ['Real Madrid', 'Manchester Utd', 'Bayern Munich', 'Juventus'];
When we use the sort( ) method, elements will be sorted in ascending order (A to Z) by default:
teams.sort();
// ['Bayern Munich', 'Juventus', 'Manchester Utd', 'Real Madrid']
If you prefer to sort the array in descending order, you need to use the reverse( ) method instead:
teams.reverse();
// ['Real Madrid', 'Manchester Utd', 'Juventus', 'Bayern Munich']
Sorting numbers is unfortunately not that simple. If we apply the sort method directly to a numbers array, we will see an unexpected result:
const numbers = [3, 23, 12];
numbers.sort(); // --> 12, 23, 3
Why the sort( ) method isn't working for numbers
Actually it is working, but this problem happens because JavaScript sorts numbers alphabetically. Let me explain this in detail.
Let's think of A=1, B=2, and C=3.
const myArray = ['C', 'BC', 'AB'];
myArray.sort(); // [AB, BC, C]
As an example, if we have three strings as C (3), BC (23) and AB(12), JavaScript will sort them as AB, BC, and C in an ascending order, which is alphabetically correct.
However, JavaScript will sort the numbers (alphabetically again) as 12, 23, and 3, which is incorrect.
Luckily, we can support the sort( ) method with a basic comparison function which will do the trick:
function(a, b) {return a - b}
The sort method, fortunately, can sort negative, zero, and positive values in the correct order. When the sort( ) method compares two values, it sends the values to our compare function and sorts the values according to the returned value.
If the result is negative, a is sorted before b.
If the result is positive, b is sorted before a.
If the result is 0, nothing changes.
All we need to is using the compare function inside the sort( ) method:
const numbers = [3, 23, 12];
numbers.sort(function(a, b){return a - b}); // --> 3, 12, 23
If we want to sort the numbers in descending order, this time we need to subtract the second parameter (b) from the first one (a):
const numbers = [3, 23, 12];
numbers.sort(function(a, b){return b - a}); // --> 23, 12, 3
So as we can see, sorting the elements of an array can be done easily in JavaScript with the sort( ) method, if we know how to use it correctly. I hope my post helps you to understand how to use the sort( ) method in JavaScript in the right way.
If you want to learn more about Web Development, feel free to visit my Youtube channel.
Thank you for reading!
No doubt this is an excellent post I got a lot of knowledge after reading good luck. Theme of blog is excellent there is almost everything to read, Brilliant post.dhamandhaman
안녕하세요, 게시글 대부분을 훑어보았습니다. 제 연구에 가장 유용한 정보를 얻은 곳이 바로 이 게시글인 것 같습니다. 올려주셔서 감사합니다. 이 주제에 대해 더 자세히 알아볼 수 있을 것 같아요. 혹시 이 주제를 다루는 다른 웹사이트를 알고 계신가요? 가락시장 노래방
I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit. situs togel online
very interesting post.this is my first time visit here.i found so mmany interesting stuff in your blog especially its discussion..thanks for the post! agen toto play login
I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog site list and will be checking back soon. Please check out my site as well and let me know what you think. duit66 link alternatif
Great article with excellent idea!Thank you for such a valuable article. I really appreciate for this great information.. Gsc108
I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. onbupkfz esfp vhaxvr
Thank you for helping people get the information they need. Great stuff as usual. Keep up the great work!!! how much does factor cost per meal
thanks for the tips and information..i really appreciate it.. situs togel online
very interesting post.this is my first time visit here.i found so mmany interesting stuff in your blog especially its discussion..thanks for the post! toto togel
This was really an interesting topic and I kinda agree with what you have mentioned here! bandar toto
저희 오피스타는 모든 오피 업체뿐만 아니라, 다양한 힐링 서비스 정보를 제공합니다. 사용자는 지역에 맞게 자신에게 맞는 업체를 손쉽게 찾아볼 수 있는 장점이 있으며, 정보를 제공하는 홈페이지의 직관적인 UI/UX를 통해 원하는 정보를 빠르게 탐색할 수 있습니다. 최고의 오피 정보를 오피스타에서 만나보세요.오피스타
Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. click for more info
[thanks this is good blog.](Kinabatangan river tour)[https://borneowildlifecruise.com/](Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.)situs slot terpercaya
I would like to say that this blog really convinced me to do it! Thanks, very good post. toro99
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. exo123.store
This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future... digital marketing services
신용카드 현금화는 현금이 필요할 때 신용카드 잔여 한도를 이용하여 카드로 결제하고, 일정 수수료를 제외한 뒤 본인 계좌로 입금을 받는 현금화 방법입니다. 허니머니에서는 삼섬카드 현금화와 햇살론 카드를 포함하여 모든 신용카드 현금화가 가능합니다. 다양한 신용카드를 결제할 수 있을 뿐만 아니라 하루에 결제할 수 있는 금액 제한 없이 편리하게 필요한 자금을 확보할 수 있습니다. 그 밖에 앱카드 결제, 상품권 현금화, 휴대폰 소액결제 등 다양한 방식의 현금화 서비스를 제공하고 있으니 24시간 고객센터를 통해 문의하여 주세요. 신용카드현금화
Vos fonds bonus correspondants à 100 % seront crédités automatiquement dans les 15 minutes suivant votre dépôt. Le bonus est assorti d'une condition de mise de 5x sur les paris combinés (minimum de 3 événements avec une cote de 1,40 ou plus chacun). Vous disposez de 30 jours pour effectuer vos mises avant l'expiration du bonus. code bonus 1xbet dj
This blog is so nice to me. I will keep on coming here again and again. Visit my link as well.. 소액 현금화
Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. 신촌가라오케
thanks this is good blog. slot online
Thank you for taking the time to publish this information very useful! kikototo link alternatif
I read that Post and got it fine and informative.toto slot 4d
Please share more like that. situs togel online
New web site is looking good. Thanks for the great effort. slot maxwin
I like this site very much so much excellent information. Rankexpert