Dans le langage de programmation JavaScript, nous sont prévues, le sort()
méthode pour trier les données d'un tableau, mais il est également utilisée pour trier autre chose qu'un tableau lui-même, et ce tutoriel vous montre JavaScript certaines méthodes populaires pour trier les données en JavaScript.
- Demo
- Agrandir
- Recharger
- New window
Gratuit iPage h�bergement Web pour la premi�re ann�e MOMENT
Si vous �tes toujours � la recherche d'un fournisseur d'h�bergement Web fiable avec des tarifs abordables, pourquoi vous ne prenez pas un peu de temps pour essayer iPage, seulement avec $1.89/month, inclus $500+ Cr�dits suppl�mentaires gratuites pour le paiement de 24 mois ($45)?
Plus de 1.000.000 de clients + existisng peuvent pas avoir tort, vraiment vous n'�tes pas aussi! Plus important encore, lorsque vous enregistrez l'h�bergement web � iPage gr�ce � notre lien, nous allons �tre heureux de renvoyer un plein remboursement. C'est g�nial! Vous devriez essayer iPage h�bergement web GRATUITEMENT maintenant! Et contactez-nous pour tout ce que vous devez savoir sur iPage.
In JavaScript, we are given a method Sort() to perform sorting. Although Sort() is said to be used for sorting an array, it can also be used to sort anything other than an array itself. In this article we will discuss all about JavaScript array.
Sort() in JavaScript
By default, the method Sort() in JavaScript takes a given array and sort it in lexicographical order and not alphabetical order! This means that the Sort() method sort a given array in dictionary order. Let’s consider the following example of Sort method.
var list =["Zebra", "Monkey", "Donkey"] list.sort() //["Donkey", "Monkey", "Zebra"]
The above look fine when sorting an array of string but when it comes to number we will face a little problem.
var list =[ 39, 108, 21, 55, 18, 9] list.sort() //[108, 18, 21, 39, 55, 9]
Looking at the result of the sort function seems to be unsorted but the fact that it is sorted according to lexicographical order does makes it in an ordered form after using the default sort method. Lucky, JavaScript doesn’t force you to follow lexicographic order. You may also define a function to sort them in your own way.
Reverse Sort()
We get our result in lexicographical order after we performed a Sort() function. What if we want the reverse order of the sort function instead? In JavaScript, there is a function Reverse() which can help us to reverse the result of the array in the opposite order of the result. Consider the following example to illustrate Reverse() method in JavaScript.
var list =["Zebra", "Monkey", "Donkey"] list.sort() //["Donkey", "Monkey", "Zebra"] list.reverse() //["Monkey", "Zebra", "Donkey"]
Simple and powerful.
Customize Sort
The default Sort() function in JavaScript is quite simple and clear. Now, we will look at how we can customize this sort function. JavaScript Sort function does take in a parameter which is a function. Short to say, Sort() Method will sort your array instructed in the given function. However, the return value of the function must be as follow,
- returns a value less than 0: parameter ‘a’ value is less than parameter ‘b’ value. ‘a’ come BEFORE ‘b’.
- returns a value greater than 0: parameter ‘a’ value is more than parameter ‘b’ value. ‘a’ come AFTER ‘b’
- returns exactly 0: parameter ‘a’ and ‘b’ have the same value. no change.
With the above rule, we can create a function that sort our array in numerical order instead of lexicographic order.
function sortmyway(data_A, data_B) { if ( data_A < data_B ) // data_A come before data_B return -1; if ( data_A > data_B ) // data_A come After data_B return 1; return 0; // data_A == data_B, no change. } var list =[ 39, 108, 21, 55, 18, 9] list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]
The above example look good but the function seems to be a bit lengthy. You can change the comparison statement in a shorter form using the ‘?’ symbol and we will get a shorter version of the code above.
function sortmyway(data_A, data_B) { return ((data_A < data_B) ? -1 : ((data_A > data_B) ? 1 : 0)); } var list =[ 39, 108, 21, 55, 18, 9] list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]
We can even shorten the above declaration to perform the same task as shown below,
function sortmyway(data_A, data_B) { return (data_A - data_B); } var list =[ 39, 108, 21, 55, 18, 9] list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]
All the methods above sort the array in ascending order.
Sort Descending order
Using the shortest method i have above, i can declare a sorting function which sort in descending order as follow,
function sortmyway(data_A, data_B) { return (data_B - data_A); } var list =[ 39, 108, 21, 55, 18, 9] list.sort(sortmyway) //[108, 55, 39, 21, 18, 9]
You can also achieve this by using the Reverse() method to eliminate the need to declare two sort function for ascending and descending order.
Random Sort Array
Well, we can also take advantage of the sort function to randomize our array. This way, we do not have to perform any loop which also contribute to function efficiency.
function sortmyway(data_A, data_B) { return 0.5 - Math.random(); //random gives us result between 0 and 1 } var list =[ 39, 108, 21, 55, 18, 9] list.sort(sortmyway) //[21, 9, 39, 108, 18, 55]
Summary
Other than array, we can also sort unordered and ordered list. Sort() method in JavaScript can help us perform different kind of sorting in every type of element not restricting to array only. However, using JavaScript to perform sort of other element other than array can be a lot of pain. Personal advice is to use JavaScript framework such as jQuery or Mootools to ease the job. On the other hand, Sort() method can also be used to substitute unnecessary loop to create a more efficient code especially when comparing each element in an array is required. (we just have to eliminate the return value to perform such task) . Even eliminating duplication in an array is possible with Sort() method!
You can find more JavaScript codes for sorting an Array at here: Algorithms by JavaScript
- Sent (0)
- Nouveau
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte
chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle
AppAIVidéo
Votre première application vidéo AI GRATUITE
Deepfake Video
Deepfake AI Video Maker
Deepfake
Deepfake AI Video Maker
AI Deep Fake
Deepfake AI Video Maker
AIvidio
AI Video Mobile Solutions
AIvideos
AI Video Platform & Solutions
AIvedio
AI Video App Maker
Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)
Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)
Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT
Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT
Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT
Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app
Your next top AI Assistant
Claude AI, developed by Anthropic
Your next top AI Assistant
Claude AI, developed by Anthropic
Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise
Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA
chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle
Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue
Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils
GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet
iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16
Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $